1. 程式人生 > >iOS 輸入框隨鍵盤上移以及點選tableView回收鍵盤

iOS 輸入框隨鍵盤上移以及點選tableView回收鍵盤

//註冊通知
-(void)viewWillAppear:(BOOL)animated{
 
    [super viewWillAppear:animated];
    
    //鍵盤出現
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //鍵盤迴收
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}
//移除通知
-(void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}
//鍵盤出現
- (void)keyboardWillShow:(NSNotification *)notification
{
    //獲取處於焦點中的view
    NSArray *textFields = @[_people_num, _scale,_leader_name,_leader_phoneNum]; //將需要上移的控制元件存在這個陣列
    UIView *focusView = nil;
    for (UITextField *view in textFields) {
        if ([view isFirstResponder]) {
            focusView = view;
            break;
        }
    }
    if (focusView) {
        //獲取鍵盤彈出的時間
        double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        //獲取鍵盤上端Y座標
    
        CGFloat keyboardY = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].origin.y;
        //獲取輸入框下端相對於window的Y座標
        CGRect rect = [focusView convertRect:focusView.bounds toView:[[[UIApplication sharedApplication] delegate] window]];
        CGPoint tmp = rect.origin;
        CGFloat inputBoxY = tmp.y + focusView.frame.size.height;
        //計算二者差值
        CGFloat ty = keyboardY - inputBoxY;
        NSLog(@"position keyboard: %f, inputbox: %f, ty: %f", keyboardY, inputBoxY, ty);
        //差值小於0,做平移變換
        [UIView animateWithDuration:duration animations:^{
            if (ty < 0) {
                self.view.transform = CGAffineTransformMakeTranslation(0, ty);
            }
        }];
    }
}


//鍵盤迴收
- (void)keyboardWillHide:(NSNotification *)notification
{
    //獲取鍵盤彈出的時間
    double duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //還原
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

將需要隨鍵盤上移的控制元件存入陣列

 NSArray *textFields = @[_people_num, _scale,_leader_name,_leader_phoneNum];

給tableView新增點選手勢

//給tableView新增手勢.  在tableView處新增以下程式碼
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyBoard)];
    tapGestureRecognizer.cancelsTouchesInView = NO;//設定成NO表示當前控制元件響應後會傳播到其他控制元件上,預設為YES。
    [self.tableView addGestureRecognizer:tapGestureRecognizer];
 //點選事件
-(void)hideKeyBoard
{
    [self.view endEditing:YES];
}