ios键盘的“Go”按钮的动作

时间:2012-10-25 09:45:46

标签: ios objective-c uitextfield uikeyboard uitextfielddelegate

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

2 个答案:

答案 0 :(得分:42)

目标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's answer以了解如何在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
    }
}

答案 1 :(得分:31)

您可以在UITextFiled中关联Did End On Exit个活动Connections Inspector。在Go中点击Return / Return Key /您选择Attributes Inspector之后触发它。

Connections Inspector