当用户按下手机键盘上的“Enter”时,如何触发测试功能的按键回调功能?
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.textfield.delegate = self
}
@IBAction func btn(_ sender: Any) {
//textfield.resignFirstResponder()
label.text = textfield.text!
print("\n func completed \n")
}
func test(textField: UITextField!) {
textfield.resignFirstResponder()
print("\n func completed \n")
}
}
你可以直接试试
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder() // options 1
self.test(textField) // option 2
self.calledFromAnyWhere() // option 3
return true
}
编辑:如果要调用按钮的操作,则首选创建共享功能
@IBAction func btn(_ sender: Any) {
self.calledFromAnyWhere()
}
func calledFromAnyWhere()
{
// any content
}
您可以添加目标来处理特定事件,如下所示:
textField.addTarget(self, action: #selector(editingDidEnd), for: .editingDidEndOnExit)
@objc func editingDidEnd() {
// Do whatever you would like here, in your case
self.btnCallback()
}