我想知道如何允许通过点击软键盘上的回车键或点击UIButton来执行一个操作。
UI按钮已经设置好执行一个IBAction。
我该如何让用户也可以通过按下键盘上的回车键来执行相同的操作呢?
确保您的类扩展了UITextFieldDelegate协议
SomeViewControllerClass : UIViewController, UITextFieldDelegate
您可以按照以下步骤执行操作:
override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
//textField code
textField.resignFirstResponder() //if desired
performAction()
return true
}
func performAction() {
//action events
}
Swift 4.2 :
对于通过编程创建且不需要委托的文本字段,还有其他方法:
MyTextField.addTarget(self, action: #selector(MyTextFielAction)
, for: UIControl.Event.primaryActionTriggered)
然后按照以下方式执行您的操作:
func MyTextFielAction(textField: UITextField) {
//YOUR CODE can perform same action as your UIButton
}
这里是一个完整的例子,包括:
按钮动作:在按下按钮时,可以执行写入和清除标签以及文本的操作,当重复按下按钮时,它会交替执行这两个操作。
键盘返回:在按下键时触发操作,并取消第一响应者。
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var label1: UILabel!
var buttonHasBeenPressed = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textField1.delegate = self
}
@IBAction func buttonGo(_ sender: Any) {
performAction()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
performAction()
return true
}
func performAction() {
buttonHasBeenPressed = !buttonHasBeenPressed
if buttonHasBeenPressed == true {
label1.text = textField1.text
} else {
textField1.text = ""
label1.text = ""
}
}
}