iOS Dev (54) 鍵盤彈出後收起時View隨之移動 – iPhone手機開發技術文章 iPhone軟體開發教學課程

iOS Dev (54) 鍵盤彈出後收起時View隨之移動

  •  
  • 添加監聽

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(changeContentViewPosition:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(changeContentViewPosition:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    

    移除監聽

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    

    事件處理函數

    - (void) changeContentViewPosition:(NSNotification *)notification{
    
        NSDictionary *userInfo = [notification userInfo];
        NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGFloat keyBoardEndY = value.CGRectValue.origin.y;
    
        NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
        NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
        [UIView animateWithDuration:duration.doubleValue animations:^{
            [UIView setAnimationBeginsFromCurrentState:YES];
            [UIView setAnimationCurve:[curve intValue]];
            self.view.center = CGPointMake(self.view.center.x, keyBoardEndY - STATUS_BAR_HEIGHT - self.view.bounds.size.height/2.0);
        }];
    }
    

    Reference

    • https://www.cnblogs.com/programmer-blog/p/3265110.html

You May Also Like