resign keyboard in UITextField

和自甴很熟 提交于 2019-12-12 03:19:13

问题


I'm working with storyboards on iOS 5 and have a simple screen that has a UITextField on it. I want to dismiss the keyboard when the user hits "Return". I followed other suggestions such as having my controller implements the UITextFieldDelegate protocol and implements textFieldShouldReturn: as follows:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [questionField resignFirstResponder];
    return YES;
}

However I see that this method is never called. I have set the controller of my view in storyboarding to my custom UIViewController.

I also tried a different implementation where I create an IBAction called dismissKeyboard but oddly I can't connect the Did Exit action to my UITextField.

Any ideas?

Update : So the problem seems to be that I'm using a UITextView and not a UITextField. I wanted a large area for the text to be entered. When I change the entry field to a UITextField it works fine. Any ideas on how to make it work with a UITextView?


回答1:


You should connect the dismiss method to the text field's Did End Editing action.




回答2:


So the solution to resign the keyboard for a UITextView is to implement shouldChangeTextInRange.




回答3:


If you want the keyboard to dismiss when tap the return key for the textview use this delegate function,

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}


来源:https://stackoverflow.com/questions/8871054/resign-keyboard-in-uitextfield

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