iOS完美实现输入框随键盘无缝滑动的效果_KLCPopKeyBoard


iOS中UITextField控件和UITextView控件经常需要对键盘做弹起和退出动作,一般使用的是becomeFirstResponder和resignFirstResponder方法,但是这样也有明显的缺点,就是会在键盘的弹起退出过程中经常出现黑边,或者断层,导致效果很不好看,在网上找了些资料,自己做了一个自定义的输入框来解决这个问题,效果类似于微信和QQ的聊天框。


不废话,直接上代码,另外做了一个demo,链接为https://github.com/didashao/KLCPopKeyBoard

KLCPopKeyBoard.h

#import <UIKit/UIKit.h>
@class KLCPopKeyBoard;
@protocol KLCPopKeyBoardDelegate <NSObject>

- (void)popKeyBoard:(KLCPopKeyBoard *)popKeyBoard didClickSend:(BOOL)didClickSend;
- (void)popKeyBoardHide;
- (void)popKeyBoardShow;

@end


@interface KLCPopKeyBoard : UIView

@property (nonatomic, weak) id<KLCPopKeyBoardDelegate> delegate;
@property (nonatomic, copy) NSString *content;//输入框内容
@property (nonatomic, copy) NSString *placeholder;

- (instancetype)initWithPlaceholder:(NSString *)placeholder buttonTitle:(NSString *)buttonTitle;

//成对使用,可以保证一直在屏幕中出现
- (void)viewWillAppear;
- (void)viewWillDisAppear;

//成对使用,可以保证单次显示
- (void)show;
- (void)hide;

//推出键盘和退出键盘
- (void)pushKeyboard;
- (void)hideKeyboard;

@end


KLCPopKeyBoard.m

#import "KLCPopKeyBoard.h"

#define KeyBoardHeight 44

#define FullScreen_Height [[UIScreen mainScreen] bounds].size.height
#define FullScreen_Width [[UIScreen mainScreen] bounds].size.width

static inline UIViewAnimationOptions NgAnimationOptionsWithCurve(UIViewAnimationCurve curve)
{
    switch (curve) {
        case UIViewAnimationCurveEaseInOut:
            return UIViewAnimationOptionCurveEaseInOut;
        case UIViewAnimationCurveEaseIn:
            return UIViewAnimationOptionCurveEaseIn;
        case UIViewAnimationCurveEaseOut:
            return UIViewAnimationOptionCurveEaseOut;
        case UIViewAnimationCurveLinear:
            return UIViewAnimationOptionCurveLinear;
    }
    return 0;
}

@interface KLCPopKeyBoard()<UITextFieldDelegate>
{
    UIView *_bgView;
    
    UITextField *_field;
    
    UIButton *_button;
    
    NSString *_placeholder;
    
    NSString *_buttonTitle;
    
    //BOOL _willHidden;
}
@end

@implementation KLCPopKeyBoard

- (instancetype)init
{
    self = [super init];
    if (self) {
        _placeholder = @"";
        _buttonTitle = @"发送";
        [self setupUI];
    }
    return self;
}

- (instancetype)initWithPlaceholder:(NSString *)placeholder buttonTitle:(NSString *)buttonTitle
{
    self = [super init];
    if (self) {
        _placeholder = placeholder;
        _buttonTitle = buttonTitle;
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    self.frame = CGRectMake(0, FullScreen_Height - KeyBoardHeight, FullScreen_Width, KeyBoardHeight);
    
    _bgView = [[UIView alloc]init];
    _bgView.frame = self.bounds;
    _bgView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_bgView];
    
    UIView *line = [[UIView alloc]init];
    line.frame = CGRectMake(0, 0, FullScreen_Width, 0.5);
    line.backgroundColor = [UIColor blackColor];
    [_bgView addSubview:line];
    
    CGFloat height = 30;
    CGFloat topMargin = (KeyBoardHeight - height)/2;
    CGFloat leftMargin = 10;
    CGFloat buttonWidth = 44;
    CGFloat buttonHeight = 30;
    
    _field = [[UITextField alloc]init];
    _field.frame = CGRectMake(leftMargin, topMargin, FullScreen_Width - leftMargin*3 - buttonWidth, height);
    _field.backgroundColor = [UIColor whiteColor];
    _field.textColor = [UIColor blackColor];
    _field.font = [UIFont systemFontOfSize:14];
    _field.returnKeyType = UIReturnKeyDone;
    _field.layer.cornerRadius = 3;
    _field.clipsToBounds = YES;
    _field.delegate = self;
    _field.placeholder = _placeholder;
    [_bgView addSubview:_field];
    
    _button = [[UIButton alloc]init];
    _button.frame = CGRectMake(CGRectGetMaxX(_field.frame)+leftMargin, topMargin, buttonWidth, buttonHeight);
    [_button setTitle:_buttonTitle forState:UIControlStateNormal];
    _button.titleLabel.font = [UIFont systemFontOfSize:14];
    _button.backgroundColor = [UIColor yellowColor];
    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _button.layer.cornerRadius = 3;
    _button.clipsToBounds = YES;
    [_button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
    [_bgView addSubview:_button];
}


#pragma mark -发送
- (void)didClickButton:(UIButton *)btn
{
    
    _content = _field.text;
    if ([_delegate respondsToSelector:@selector(popKeyBoard:didClickSend:)]) {
        [_delegate popKeyBoard:self didClickSend:YES];
        _field.text = nil;
        [self hideKeyboard];
    }
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    _field.placeholder = placeholder;
}

#pragma mark - 展示控制
- (void)viewWillAppear
{
    [self show];
}

- (void)viewWillDisAppear
{
    [self hide];
}

- (void)show
{
    dispatch_async(dispatch_get_main_queue(), ^{
        for (UIView *view in [UIApplication sharedApplication].keyWindow.subviews) {
            if ([view isKindOfClass:[KLCPopKeyBoard class]]) {
                return;
            }
        }
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        [[UIApplication sharedApplication].keyWindow bringSubviewToFront:self];
    });
}

-(void)hide
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self removeFromSuperview];
    });
    /*
    if ([_field isFirstResponder]) {
        _willHidden = YES;
        [self hideKeyboard];
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeFromSuperview];
        });
    }*/
}

#pragma mark - 推出和退出键盘
- (void)pushKeyboard
{
    if (![_field isFirstResponder]) {
        [_field becomeFirstResponder];
        if ([_delegate respondsToSelector:@selector(popKeyBoardShow)]) {
//            [_delegate popKeyBoardShow];
        }
    }
}

- (void)hideKeyboard
{
    if ([_field isFirstResponder]) {
        [_field resignFirstResponder];
        if ([_delegate respondsToSelector:@selector(popKeyBoardHide)]) {
            [_delegate popKeyBoardHide];
        }
    }
}

#pragma mark - 键盘监听
- (void)startListenKeyboard
{
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(onKeyboardWillShow:)
     name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(onKeyboardWillHide:)
     name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(onKeyboardDidShow:)
     name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(onKeyboardDidHide:)
     name:UIKeyboardDidHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(onKeyboardWillChangeFrame:)
     name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(onKeyboardDidChangeFrame:)
     name:UIKeyboardDidChangeFrameNotification object:nil];
}

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

- (void)onKeyboardWillShow:(NSNotification *)note {
    
    
}
- (void)onKeyboardDidShow:(NSNotification *)note {
    


}
- (void)onKeyboardWillHide:(NSNotification *)note {
    if ([_delegate respondsToSelector:@selector(popKeyBoardHide)]) {
        [_delegate popKeyBoardHide];
    }
    
}
- (void)onKeyboardDidHide:(NSNotification *)note {
    
}

- (void)onKeyboardWillChangeFrame:(NSNotification *)note {
    //Log("%@",note.userInfo);
    [self captureKeyboardFrameWithInfo:note.userInfo];
}
- (void)onKeyboardDidChangeFrame:(NSNotification *)note {
    //Log("%@",note.userInfo);
    //[self captureKeyboardFrameWithInfo:note.userInfo];
}

- (void)captureKeyboardFrameWithInfo:(NSDictionary *)info
{
    CGRect _endFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval _animationDuration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve animationCurve = (UIViewAnimationCurve)[info[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    [UIView animateWithDuration:_animationDuration delay:0 options:NgAnimationOptionsWithCurve(animationCurve) animations:^{
        CGRect myFrame = self.frame;
        myFrame.origin.y = _endFrame.origin.y - KeyBoardHeight;
        self.frame = myFrame;
    } completion:^(BOOL finished) {
        /*if (_willHidden) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self removeFromSuperview];
            });
            _willHidden = NO;
        }*/
    }];
}

#pragma mark - TextField delegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([_delegate respondsToSelector:@selector(popKeyBoardHide)]) {
        [_delegate popKeyBoardShow];
    }
    
    [self startListenKeyboard];
    return YES;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.content = textField.text;
    [self endListenKeyboard];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
//    [textField resignFirstResponder];
//    if ([_delegate respondsToSelector:@selector(popKeyBoard:didClickSend:)]) {
//        [_delegate popKeyBoard:self didClickSend:YES];
//        _field.text = nil;
//        if ([_delegate respondsToSelector:@selector(popKeyBoardHide)]) {
//            [_delegate popKeyBoardHide];
//        }
//    }
    
    [self didClickButton:nil];
    
    return YES;
}

@end



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现iOS的聊天输入框功能,可以按照以下步骤进行: 第一步,创建一个包含输入框的视图控制器。可以使用UITextField或UITextView来创建输入框,并设置好相应的属性,例如输入框的大小、位置、边框样式等。 第二步,设置输入框的代理。通过设置输入框的代理,可以监听输入框的文字变化、键盘弹出和隐藏等事件,并做出相应的处理。 第三步,实现输入框的自动调整高度功能。聊天输入框通常需要根据输入的文字内容自动调整高度,以方便用户输入长文本。可以通过监听输入框的文字变化,并计算输入框内容所需的高度,然后实时更新输入框的高度。 第四步,处理键盘弹出和隐藏。当用户点击输入框时,系统会自动弹出键盘。为了不遮挡输入框,需要将输入框键盘弹出而上移,以保证用户能够看到正在输入的文字。可以使用NSNotification来监听键盘弹出和隐藏事件,并相应地更新输入框的位置。 第五步,实现发送按钮的功能。在聊天输入框中一般会有一个发送按钮,用于发送消息。可以通过添加一个UIButton,并设置好按钮的样式和位置。然后,监听发送按钮的点击事件,并处理发送消息的逻辑,例如将消息发送到服务器或本地数据库。 在实现聊天输入框功能的过程中,还可以根据需求添加一些其他的功能,如表情符号的支持、附件的发送等。通过以上步骤,就可以实现一个基本的聊天输入框功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值