iOS 键盘遮挡 页面上移

2017-05-08  本文已影响112人  李栖桐

适配不同型号的键盘大小

@property (nonatomic, assign)CGSize kbSize;

viewDidLoad

[self registerForKeyboardNotifications];

各种方法


- (void)registerForKeyboardNotifications{
    
    //使用NSNotificationCenter 键盘出现时
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardDidShowNotification object:nil];
    
}

- (void)keyboardWillShow:(NSNotification*)notify
{

    NSDictionary* info = [notify userInfo];
    //kbSize键盘尺寸 (有width, height)
    self.kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//键盘高度
    NSLog(@"hight_hight:%f",self.kbSize.height);

    CGRect currentFrame = self.view.frame;
    CGFloat change =self.kbSize.height;
    currentFrame.origin.y = currentFrame.origin.y - change ;

    [UIView animateWithDuration:0.00000000001 animations:^{
        self.view.frame = currentFrame;
    }];
}

///键盘消失事件
- (void) keyboardWillHidden {
    
    //视图下沉恢复原状
    [UIView animateWithDuration:0.00000000001 animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
    
    [【你的TextFiled】 resignFirstResponder];

}

// 视图将要消失时,移除通知中心
-(void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
上一篇下一篇

猜你喜欢

热点阅读