swift - 将 TapGestureRecognizer 添加到 TextField

标签 swift uitextfield

我所有的 UiTextField 都是以编程方式创建的,所以我不能只是右键单击并将 onTab 函数拖放到 swift 文件中。

我尝试向文本字段添加手势识别器,但现在我必须双击才能触发 clickTextField()。

// make clickable
let clickName = MyTapGesture(target: self, action: #selector(ViewMain.clickTextField(_:)))
clickName.count_of_selection = String(i)
self.finishName[i].addGestureRecognizer(clickName)

我怎样才能让它一键工作。也许是一种不同的方法?

最佳答案

UITextField 有一个点击手势。您需要使用它的委托(delegate)方法:

func textFieldShouldBeginEditing(_ textField: UITextField)
func textFieldDidEndEditing(_ textField: UITextField)
func textFieldShouldEndEditing(_ textField: UITextField)
func textFieldDidBeginEditing(_ textField: UITextField)
func textFielShouldClear(_ textField: UITextField)
func textFielShouldReturn(_ textField: UITextField)

不要忘记

yourTextField.delegate = self

在你为你的 vc 创建一个扩展之后:

extension ViewController: UITextFieldDelegate {
    // here you add the necessary delegate methods for your textFields
}

注意:您不需要实现每个方法。只使用你需要的那个。更多详细信息,请访问 AppleDeleveloper .

关于swift - 将 TapGestureRecognizer 添加到 TextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53400439/

相关文章:

swift - 将 guard 与非可选值赋值一起使用

ios - 将 UIScrollView 偏移从 Swift 4 中的另一个 viewController 更改为顶部

iphone - 限制在数字文本字段中复制粘贴字符串

ios - swift 提出 Unresolved 标识符

swift - 关闭时模态 Controller 仍然是最顶层的 View Controller

ios - 使用键值对在 Swift 中发布请求

uitextfield - iOS 13 - 带有占位符的 UITextField 让应用程序崩溃

ios - 在 Swift 中获取和设置 UITextField 和 UITextView 的光标位置

ios - UIPickerview 的 UITextfield 问题

objective-c - 带有 UITextField 的 UIPicker