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

前端 未结 5 1997
一向
一向 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-12 23:57

    Here is a complete example, with both:

    1. button-action to write and also to clear label and text when pressing button repeatedly it alternates both actions

    2. return-in-keyboard when pressing key it triggers action and also resigns first responder

    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 = ""
            }
            
        }
        
    }

提交回复
热议问题