在 swift 中检测何时按下文本字段

Detect when textfield has been pressed in swift

我想在按下某个文本字段时执行一个操作。我试过了

func textFieldDidBeginEditing(_ textField: UITextField) {

    if textField == myTextField {
        print("pressed")
    }
}

但这对我不起作用。有没有人有任何解决方案?谢谢

此函数是来自UITextFieldDelegate 的回调。但只有当 class 与 this 连接到您的 UITextField 的委托时,它才会被触发。

使用 iOS ViewController 的简单示例:

class yourViewController: UIViewController, UITextFieldDelegate
{
    /* Make sure that your variable 'myTextField' was created using an IBOutlet from your storyboard*/
    @IBOutlet var myTextField : UITextField!

    override func ViewDidLoad()
    {
         super.viewDidLoad()
         myTextField.delegate = self // here you set the delegate so that UITextFieldDelegate's callbacks like textFieldDidBeginEditing respond to events
    }



    func textFieldDidBeginEditing(_ textField: UITextField) {

    if textField == myTextField {
    print("pressed")
        }
    }

}

请确保您了解委托模式事件处理的概念,以及委托如何捕获和发布像这样的事件。许多 Cocoa GUI 组件都使用这种设计。这些是一些有用的链接。

https://docs.swift.org/swift-book/LanguageGuide/Protocols.html

https://developer.apple.com/documentation/uikit/uitextfielddelegate

http://www.andrewcbancroft.com/2015/03/26/what-is-delegation-a-swift-developers-guide/