iOS動態獲取鍵盤高度實現流暢的鍵盤輸入框開發

新項目迭代中有個類似短信或QQ微信輸入框隨鍵盤推出的UI需求。
按照常用方法有兩種:
1.註冊通知動態獲取鍵盤高度
2.自定義UITextField的inputView
下面是親測流暢有效的通知監測獲取鍵盤高度法:

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //添加通知
    [self registerForKeyboardNotifications];

}

添加兩個通知,UIKeyboardWillShowNotification,當鍵盤即將出現的時候,實現自定義帶輸入框的視圖或其他UI控件的添加,UIKeyboardWillHideNotification,鍵盤即將隱藏的時候實現輸入框移動到下沉到底部

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
}

在實現鍵盤即將出現方法的時候注意,此方法每次會走兩遍,所以創建其他控件時要避免重複創建添加多次:

- (void) keyboardWasShown:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    NSLog(@"keyBoardheight = :%f", keyboardSize.height); 
    [UIView animateWithDuration:0.25 animations:^{
        CGRect rect = self.footerView.frame;
        rect.origin.y = ScreenHeight-keyboardSize.height-49- self.separateView.bottom - 20;
        self.footerView.frame = rect;

    } completion:^(BOOL finished) {
        nil;
    }];
    //可避免重複創建添加
    if (!_translucenceView) {
        _translucenceView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-keyboardSize.height-49)];
         _translucenceView.backgroundColor = COLOR(0, 0, 0, 0.5);
    }

}

可把視圖下移的動畫寫在下面方法裏,textField通過調用resignFirstResponder方法即可調動此方法。

- (void) keyboardWasHidden:(NSNotification *) notif
{
    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.footerView.frame;
        frame.origin.y = ScreenHeight - 49 - self.separateView.bottom - 20;
        self.footerView.frame = frame;
    }];
    [self.translucenceView removeFromSuperview];
    self.translucenceView = nil;

}

OK,親測收縮流暢的輸入框就成了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章