蓝天,小湖,湖水中一方小筑

Dismiss keyboard in UITextViewController

The method is collected from Internet and I just record it with my way.

First create a single view project, then drag an UITextViewController, an UINavigationBar and an UINavigationItem into the storyboard. Link the three elements to the ViewController class by dragging with Ctrl key. The view controller should implement the UITextViewDelegate, then add some code to the function invoked while beginning and completing edit. This sample add one button on the navigation bar to dismiss the keyboard, and the button will be shown and hidden dynamically. Function textViewDidBeginEditing and textViewDidBeginEditing will be used to implement the feature:

- (void) textViewDidBeginEditing:(UITextView *)textView {
    UIBarButtonItem *send = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(leaveEditMode)];
    self.navItem.rightBarButtonItem = send;
}

- (void) textViewDidEndEditing:(UITextView *)textView {
    self.navItem.rightBarButtonItem = nil;
}

And here is the function leaveEditMode, which will dismiss the keyboard.

- (void) leaveEditMode {
    [self.content resignFirstResponder];
}

That’s all.