我想知道你如何允许一个行动,要么按下软件键盘上的返回键或通过点击一个 UIButton。
UI 按钮已经设置为执行 IBAction。
如何允许用户按键盘上的返回键执行相同的操作?
如果您的部署目标是 iOS 9.0或更高版本,您可以将文本字段的“主要操作触发”事件连接到一个操作,如下所示:
使您的视图控制器采用 UITextFieldDelegate协议。
UITextFieldDelegate
将文本字段的委托设置为视图控制器。
实现 textFieldShouldReturn:来调用您的操作。
textFieldShouldReturn:
确保您的类扩展了 UITextFieldCommittee 协议
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 }
我无法使“主要行动触发”按建议工作。我使用“编辑已经结束”,现在的工作 剪辑结束截图
下面是一个完整的例子,两者都有:
按钮-行动写,也清除标签和文字时,按下按钮反复交替这两个行动
当按键时返回键盘,它触发行动,也辞职第一响应者
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 = "" } } }
迅捷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 }