关闭键盘的几种方式
(1)如果你程序是有导航条的,可以在导航条上面多加一个Done的按钮,用来退出键盘。代码如下:
- (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.myTextView resignFirstResponder];
}
(2)如果你的textview里不用回车键,可以把回车键当做退出键盘的响应键。代码如下:
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"])
{
[textView resignFirstResponder];
return NO;
}
return YES;
}
(3)也可以在弹出的键盘上面加一个view来放置退出键盘的Done按钮。代码如下:
#import "ViewController.h"
@implementation ViewController
@synthesize myTextView;
#pragma mark - view life cycle
- (void)viewDidLoad
{
[super viewDidLoad];
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];
[topView setItems:buttonsArray];
[doneButton release];
[btnSpace release];
[helloButton release];
[self.myTextView setInputAccessoryView:topView];
}
- (void)dismissKeyBoard
{
[self.myTextView resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}