How do I get the return key to perform the same action as a button press in Swift?

前端 未结 5 1992
一向
一向 2020-12-12 23:42

I want to know how you allow an action to be made by either pressing the return key on the software keyboard or by tapping a UIButton.

The UI button is already set u

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 00:05

    Make sure your class extends the UITextFieldDelegate protocol

    SomeViewControllerClass : UIViewController, UITextFieldDelegate
    

    You can perform action as follows:

    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
    }
    

提交回复
热议问题