20

如何在 iOS 中将操作绑定到键盘的Go按钮?

4

2 回答 2

42

Objective-C

假设您使用的是 UITextField,您可以使用<UITextFieldDelegate>方法textFieldShouldReturn

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

    return YES;
}

不要忘记将您放入此代码的类指定为文本字段的委托。

self.someTextField.delegate = self;

或者,如果您更喜欢使用 UIControlEvents,您可以执行以下操作

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

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

请参阅@Wojtek Rutkowski 的回答,了解如何在 Interface Builder 中执行此操作。

迅速

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
    }
}
于 2012-10-25T09:51:09.363 回答
31

UITextFiled可以Did End On ExitConnections Inspector. Go在点击/ Return / 您选择的任何内容Return Key后触发它,如Attributes Inspector.

连接检查员

于 2012-10-25T10:36:46.443 回答