Action of the “Go” button of the ios keyboard

故事扮演 提交于 2019-11-30 11:44:34

问题


How do I bind an action to the Go button of the keyboard in iOS ?


回答1:


Objective-C

Assuming you're using a UITextField, you could use the <UITextFieldDelegate> method textFieldShouldReturn.

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder]; // Dismiss the keyboard.
    // Execute any additional code

    return YES;
}

Don't forget to assign the class you put this code in as the text field's delegate.

self.someTextField.delegate = self;

Or if you'd prefer to use UIControlEvents, you can do the following

[someTextField addTarget:self action:@selector(textFieldDidReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];

- (void)textFieldDidReturn:(UITextField *)textField
{
    // Execute additional code
}

See @Wojtek Rutkowski's answer to see how to do this in Interface Builder.

Swift

UITextFieldDelegate

class SomeViewController: UIViewController, UITextFieldDelegate {
    let someTextField = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()

        someTextField.delegate = self
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder() // Dismiss the keyboard
        // Execute additional code
        return true
    }
}

UIControlEvents

class SomeViewController: UIViewController {
    let someTextField = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Action argument can be Selector("textFieldDidReturn:") or "textFieldDidReturn:"
        someTextField.addTarget(self, action: "textFieldDidReturn:", forControlEvents: .EditingDidEndOnExit)
    }

    func textFieldDidReturn(textField: UITextField!) {
        textField.resignFirstResponder()
        // Execute additional code
    }
}



回答2:


You can connect UITextFiled event Did End On Exit in Connections Inspector. It is triggered after tapping Go / Return / whatever you choose as Return Key in Attributes Inspector.



来源:https://stackoverflow.com/questions/13065868/action-of-the-go-button-of-the-ios-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!