IOS develops UITextView to recycle or close the keyboard
- 2020-05-24 05:57:22
- OfStack
IOS develops UITextView to recycle or close the keyboard
In the development of iOS, it is found that UITextView does not have a method like textFieldShouldReturn: in UITextField. In order to achieve UITextView to close the keyboard, other methods must be used. The following are several methods that can be used.
1. If your application has a navigation bar, you can add an Done button to the navigation bar to exit the keyboard.
- (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 don't use the enter key in your textview, use the enter key as a response to the exit keyboard.
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
return YES;
}
Whether you use the enter key on your computer keyboard or the return key in the pop-up keyboard, you can exit the keyboard.
3. The third method, which feels better than the above two, is to add an view to 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];
}
Thank you for reading, I hope to help you, thank you for your support of this site!