Swift UITextFieldShouldReturn Return Key Tap

后端 未结 4 1901
旧时难觅i
旧时难觅i 2021-02-01 01:26

(iOS8, Xcode6, Swift) Using Swift, how do I capture a tap on the \"Return\" button?

The doc at the following link specifies using the textFieldShouldReturn

相关标签:
4条回答
  • 2021-02-01 01:53

    You need to set an object as the text field's delegate. Usually that would be the view controller that the text field exists in. You don't need to inherit from any other class, or, strictly speaking, implement a delegate (but you could implement UITextFieldDelegate to make things a little clearer.)

    0 讨论(0)
  • 2021-02-01 01:59
    class ViewController: UIViewController,UITextFieldDelegate //set delegate to class
    
    @IBOutlet var txtValue: UITextField //create a textfile variable
    
    override func viewDidLoad() {
       super.viewDidLoad() 
       txtValue.delegate = self //set delegate to textfile 
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
       textField.resignFirstResponder()
       return true
    }
    
    0 讨论(0)
  • 2021-02-01 02:06

    In Swift 4.2 and Xcode 10.1

    //UITextField delegate method
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    
        if textField == TF1 {
            textField.resignFirstResponder()//
            TF2.becomeFirstResponder()//TF2 will respond immediately after TF1 resign.
        } else if textField == TF2  {
            textField.resignFirstResponder()
            TF3.becomeFirstResponder()//TF3 will respond first
        } else if textField == TF3 {
            textField.resignFirstResponder()
        }
        return true
    }
    
    0 讨论(0)
  • 2021-02-01 02:07

    Implement this function

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
       textField.resignFirstResponder()
       return true
    }
    

    And for delegate you can set using the Utilities pane / Connections Inspector / delegate and then drag to ViewController (yellow button in the storyboard)

    Then you do not need to set the delegate programmatically for every text field

    0 讨论(0)
提交回复
热议问题