iOS--UITextView 与 键盘处理

 

1.遵守协议。UITextViewDelegate

2.调用方法,点击空白区域,收回键盘

#pragma mark - 点击空白区域,收回键盘
- (void)setBackKeyboard {
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [notiCenter addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    
                    [self addGestureRecognizer:singleTapGR];
                }];
    [notiCenter addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    
                    [self removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapBackKeyboard:(UIGestureRecognizer *)tap {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self endEditing:YES];
}

3.点击return 收回键盘

#pragma mark UITextViewDelegate 点击return收回键盘

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    
    if ([text isEqualToString:@"\n"]) {
        
        
        
        [textView resignFirstResponder];
        
        return NO;
    }
    
    
    return YES;
    
    
}

4.处理键盘的遮挡

#pragma mark UITextViewDelegate--开始编辑
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    if (iPhone5) {
        CGFloat offset_y = 0.f;
        if (textView.tag == 1000) {//获取到textView
            offset_y = 200.f;//偏移的位置
        }
        CGPoint point = self.tableView.contentOffset;
        point = CGPointMake(point.x, offset_y);
        [UIView animateWithDuration:0.25 animations:^{
            self.tableView.contentOffset = point;
        }];
    }
    return YES;
}

#pragma mark UITextViewDelegate--结束编辑
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    if (iPhone5) {
        CGFloat offset_y = 0.f;
        if (textView.tag == 1000) {
            offset_y = 200.f;
        }
        CGPoint point = self.tableView.contentOffset;
        point = CGPointMake(point.x, 0);
        [UIView animateWithDuration:0.25 animations:^{
            self.tableView.contentOffset = point;
        }];
    }
    return YES;
}

5.处理通知

-(void)dealloc
{
   
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
    
}

 

转载于:https://my.oschina.net/huangyn/blog/1605100

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值