我想在按下某个文本框时采取措施。我尝试过
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == myTextField {
print("pressed")
}
}
但这对我不起作用。有人有解决方案吗?谢谢
答案 0 :(得分:1)
此函数是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/