解决IQKeyboard键盘引起的视图上移

由于IQKeyboard键盘功能强大,所有很多人都在用,但难免会和项目有冲突,比如整体视图上移。。。
下面说一下我的解决方案,为了不影响其他页面的使用,所以在使用的页面停掉IQKeyboard键盘,然后自己监听键盘弹出的方法,来执行操作

首先在引入IQKeyboard键盘的头文件

1.在页面出现时关闭键盘,在页面消失开启键盘,不影响其他页面键盘的使用
-(void)viewWillAppear:(BOOL)animated {
    
    //关闭键盘事件相应
    [IQKeyboardManager sharedManager].enable = NO;
}

-(void)viewWillDisappear: (BOOL)animated {
    
    //打开键盘事件相应
    [IQKeyboardManager sharedManager].enable = YES;
}

2.在viewDidLoad监听键盘的弹出和消失事件

//键盘将要显示时候的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    //键盘将要结束时候的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boardDidHide:) name:UIKeyboardWillHideNotification object:nil];

3.执行监听事件的方法,进行相应的操作

//键盘将要显示
-(void)boardWillShow:(NSNotification *)notification{
    
    //获取键盘高度,
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
  //键盘弹出的时间
[[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]

    [UIView animateWithDuration:[[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
        
      //改变输入框的y值和view的高度
        self.bottomView.y = kHeight - 50 - kbHeight;
        self.mainTableView.height = kHeight - 50 - kbHeight;
        
    }];
    
}

//键盘将要结束
-(void)boardDidHide:(NSNotification *)notification{
    
     //恢复输入框的y值和view的高度
    self.bottomView.y = kHeight - 50 ;
    self.mainTableView.height = kHeight - 50;
    self.messageView.placeholder = @"请输入留言信息";
    
}


4.隐藏键盘上自动添加的工具条

[IQKeyboardManager sharedManager].enableAutoToolbar = NO;

5.可以将键盘上的return按键,变为Next/Done按键,默认最后一个UITextField/UITextView的键盘return键变为Done。顺序是按照创建控件的先后顺序,而不是从上到下的摆放顺序。

#import 
@implementation ViewController
{
    IQKeyboardReturnKeyHandler *returnKeyHandler;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    returnKeyHandler = [[IQKeyboardReturnKeyHandler alloc] initWithViewController:self];
}

6.设置点击背景收回键盘

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
}

7.如果你的视图有导航栏,键盘弹起不想导航栏被弹出视图,需要把当前的View替换为UIScrollView

-(void)loadView
{
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.view = scrollView;
}

你可能感兴趣的:(解决IQKeyboard键盘引起的视图上移)