UITextView: reclaim or close the keyboard, and uitextview reclaim the keyboard
During iOS development, it is found that UITextView does not have such a method as textFieldShouldReturn in UITextField. To enable UITextView to close the keyboard, you must use other methods. Below are several methods that can be used.
1. If your program has a navigation bar, you can add a Done button on the navigation bar to exit the keyboard. Of course, you must first implement UITextViewDelegate.
-(Void) textViewDidBeginEditing :( UITextView *) textView {
UIBarButtonItem * done = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemDone target: self action: @ selector (leaveEditMode)] autorelease];
Self. navigationItem. rightBarButtonItem = done;
}
-(Void) textViewDidEndEditing :( UITextView *) textView {
Self. navigationItem. rightBarButtonItem = nil;
}
-(Void) leaveEditMode {
[Self. textView resignFirstResponder];
}
2. If you do not need the Enter key in textview, you can use the Enter key as the response key to exit the keyboard.
-(BOOL) textView :( UITextView *) textView shouldChangeTextInRange :( nsange) range replacementText :( NSString *) text
{
If ([text isEqualToString: @ "\ n"]) {
[TextView resignFirstResponder];
Return NO;
}
Return YES;
}
In this way, whether you use the Enter key on the keyboard or the return key in the pop-up keyboard, you can exit the keyboard.
3. The third method is better than the above two methods, that is, add a view on the pop-up keyboard to place the Done button to exit the keyboard.
UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
[topView setBarStyle:UIBarStyleBlack];
UIBarButtonItem * helloButton = [[UIBarButtonItem alloc]initWithTitle:@"Hello" style:UIBarButtonItemStyleBordered target:self action:nil];
UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
NSArray * buttonsArray = [NSArray arrayWithObjects:helloButton,btnSpace,doneButton,nil];
[doneButton release];
[btnSpace release];
[helloButton release];
[topView setItems:buttonsArray];
[tvTextView setInputAccessoryView:topView];
-(IBAction)dismissKeyBoard
{
[tvTextView resignFirstResponder];
}