IOS自定义键盘顶部输入区并且实时计算高度

相关链接:
iOS-自定义emoji表情键盘
IOS 仿支付宝充值数字键盘
demo传送门:https://github.com/xinsun001/XSKeyboardView/tree/main

想要做出来的效果大概是这样的:


Screenflick Movie 5.gif

对于输入区的frame更新比较简单,使用系统的键盘通知就可以了

- (void)keybordChanged:(NSNotification *)notification{
    
    self.lenFrame = [notification.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    
    [UIView animateWithDuration:0.25 animations:^{
        
        CGRect resultFrame ;
        
        if (self.lenFrame.origin.y ==  ViewAllHeight) {
            
            resultFrame=CGRectMake(0,  ViewAllHeight,  ViewAllWidth, self.keyInputH);
            
        }else{
            resultFrame=CGRectMake(0,  ViewAllHeight-self.lenFrame.size.height-self.keyInputH,  ViewAllWidth, self.keyInputH);
            
        }
        
        self.topInputView.frame = resultFrame;
        
    }];
}

难点是如果根据用户输入的文本来实时更新输入区的高度,我在网上找到的这个方法

//给一个初始的高度
NSInteger inputH=55;
    
    float textViewWidth=ViewAllWidth-(20+30+10+20);//取得文本框宽度

    NSString *content=textView.text;
    NSDictionary *dict=@{NSFontAttributeName:[UIFont systemFontOfSize:15]};
    CGSize contentSize=[content sizeWithAttributes:dict];//计算文字长度
    float numLine=ceilf(contentSize.width/textViewWidth); //计算当前文字长度对应的行数
    //判断用户输入有值的情况
if (numLine>1) {
        //毕竟高度不能无限扩展,要设置一个最大的值
        if (numLine>4) {
            inputH=inputH+17*3;

        }else{
            inputH=inputH+17*(numLine-1);

        }

    }else{
        inputH=inputH;

    }

if (self.textViewHeightBlock) {
        self.textViewHeightBlock(inputH);
    }

获取到了实时高度,然后到主控制器去更新一下输入区的整个frame就可以了

[self.topInputView setTextViewHeightBlock:^(NSInteger height) {
       
        weakSub.keyInputH=height;
        
        [weakSub relpodInoutH:height];

    }];
-(void)relpodInoutH:(NSInteger)keyInputH{

    [UIView animateWithDuration:0.2f animations:^{
        CGRect frame1 = self.topInputView.frame;
        frame1.size.height=keyInputH;
        if (self.lenFrame.origin.y ==  ViewAllHeight) {
            frame1.origin.y=self.topInputView.frame.origin.y;

        }else{
            frame1.origin.y=ViewAllHeight-self.lenFrame.size.height-keyInputH;

        }
        frame1.origin.x=self.topInputView.frame.origin.x;
        frame1.size.width=self.topInputView.bounds.size.width;
        self.topInputView.frame=frame1;

    }];
}

是不是很简单

demo传送门:https://github.com/xinsun001/XSKeyboardView/tree/main

你可能感兴趣的:(IOS自定义键盘顶部输入区并且实时计算高度)