UITextView关闭键盘

1.如果你程序是有导航条的,可以在导航条上面加多一个Done的按钮,用来退出键盘,当然要先实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.如果你的textview里不用回车键,可以把回车键当做退出键盘的响应键。
代码如下:
#pragma mark - UITextView Delegate Methods   
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text  
{  
    if ([text isEqualToString:@"\n"]) {  
        [textView resignFirstResponder];  
        return NO;  
    }  
    return YES;  
}  

这样无论你是使用电脑键盘上的回车键还是使用弹出键盘里的return键都可以达到退出键盘的效果。

3.第三种方法感觉效果比上面两种都好,就是在弹出的键盘上面加一个view来放置退出键盘的Done按钮。
- (void) initFeedText{
    //初始化 UITextView
    CGRect frame = CGRectMake(12, 0, 160, 88);
    textFeed = [[UITextView alloc] initWithFrame:frame];
    textFeed.delegate = self;
    textFeed.font = [UIFont fontWithName:@"TrebuchetMS" size:16];
    textFeed.backgroundColor = [UIColor clearColor];
    textFeed.autocorrectionType = UITextAutocorrectionTypeYes;
    textFeed.autocapitalizationType = UITextAutocapitalizationTypeNone;
    textFeed.keyboardType = UIKeyboardTypeDefault;
    textFeed.returnKeyType = UIReturnKeyDone;
    textFeed.delegate = self;
    
    //在弹出的键盘上面加一个view来放置退出键盘的Done按钮
    UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];  
    [topView setBarStyle:UIBarStyleDefault];
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];    
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace, doneButton, nil]; 
    [btnSpace release];
    [doneButton release];
    [topView setItems:buttonsArray];
    [textFeed setInputAccessoryView:topView];
    [topView release];
}

//关闭键盘
-(void) dismissKeyBoard{
    [textFeed resignFirstResponder];
}


推荐第三种,很好用~

你可能感兴趣的:(UITextView)