如何让返回键执行与 Swift 中按钮相同的操作?

我想知道你如何允许一个行动,要么按下软件键盘上的返回键或通过点击一个 UIButton。

UI 按钮已经设置为执行 IBAction。

如何允许用户按键盘上的返回键执行相同的操作?

74604 次浏览

更新

如果您的部署目标是 iOS 9.0或更高版本,您可以将文本字段的“主要操作触发”事件连接到一个操作,如下所示:

connecting primary action triggered event

原创的

使您的视图控制器采用 UITextFieldDelegate协议。

将文本字段的委托设置为视图控制器。

实现 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
}

如果您的部署目标是 iOS 9.0或更高版本,您可以将文本字段的“主要操作触发”事件连接到一个操作,如下所示:

我无法使“主要行动触发”按建议工作。我使用“编辑已经结束”,现在的工作 剪辑结束截图

enter image description here

下面是一个完整的例子,两者都有:

  1. 按钮-行动写,也清除标签和文字时,按下按钮反复交替这两个行动

  2. 当按键时返回键盘,它触发行动,也辞职第一响应者

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
}