繁体   English   中英

快速检测何时按下文本框

[英]Detect when textfield has been pressed in swift

我想在按下某个文本框时采取措施。 我努力了

func textFieldDidBeginEditing(_ textField: UITextField) {

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

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

此函数是UITextFieldDelegate的回调。 但是,只有与此相关的类连接到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/

暂无
暂无

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

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