textView取消键盘


1、通过在textView中键盘上方添加一个toolBar来实现取消键盘的功能,可以添加其他功能:
1 UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];  
2     [topView setBarStyle:UIBarStyleBlackTranslucent];
3     
4     UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
5     UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];    
6     NSArray * buttonsArray = @[btnSpace, doneButton];    
7     
8     [topView setItems:buttonsArray];
9     [_textView setInputAccessoryView:topView];
2、如果上方有一个navigationBar,则可以在bar上添加一个DONE按钮来取消键盘,如果bar上已经有其他功能按键,则可以弹出键盘前保存当前barButtonItem,然后在弹出键盘(利用shouldBeginEditing委托来触发)后用取消键盘按钮来替换:
1 - (BOOL)textViewShouldBeginEditing:(UITextView *)textView
2 {
3     self.rightButton = self.navigationItem.rightBarButtonItem;
4     UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)]; 
5     self.navigationItem.rightBarButtonItem = doneButton;
6     return YES;
7 }

键盘消失后再赋回原来的按钮:
- (void)dismissKeyBoard
{
    [_textView resignFirstResponder];
    self.navigationItem.rightBarButtonItem = self.rightButton;
}

 


 

 
posted @ 2012-12-23 22:28  Story Of My Life  阅读(1406)  评论(0编辑  收藏  举报