简体   繁体   English

如何在Swift 2的UITextField上检测点击?

[英]How to detect tap on UITextField for Swift 2?

Is there an documentation or example on how do I do it in Swift 2? 是否有关于如何在Swift 2中进行操作的文档或示例?

I have read many articles but it doesn't provide much details beside jumping into the codes which are mostly done in Objective-C / Swift 1. 我读了很多文章,但是除了跳入大部分在Objective-C / Swift 1中完成的代码之外,它没有提供太多细节。

You can set tag on textfield in Attribute Inspector or through programatically 您可以在Attribute Inspector中的文本字段上或通过编程设置标签

 myTextfield.tag = 1 //AnyValue
 myTextfield.delegate = self

Now, Implement textfield delegate method and check for which textfield edited 现在,实现textfield委托方法并检查编辑了哪个textfield

 func textFieldShouldBeginEditing(textField: UITextField) -> Bool {

    if textField.tag == 1{
       //do here you want
    }
    return true
 } 

You can check if a UITextField became first responder to know if one was tapped. 您可以检查UITextField成为第一响应者,以了解是否已点击。 You need to set the delegate of UITextField for example: 您需要设置UITextField的委托,例如:

@IBOutlet weak var textField: UITextField! { didSet { textField.delegate = self } }

Where self is a UIViewController conforming to UITextFieldDelegate 其中self是符合UITextFieldDelegateUIViewController

Now you can check if a UITextField became first responder with: 现在,您可以使用以下命令检查UITextField成为第一响应者:

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    print("textField did became first responder")
    return true
}

You return true to let the textfield become first responder (unless that is not the behaviour you wish, then return false) and before the return statement you can do anything you want. 您返回true以使文本字段成为第一响应者(除非不是您希望的行为,然后返回false),并且在return语句之前您可以执行任何所需的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM