處理鍵盤上升蓋住文本框問題

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //註冊觀察鍵盤的變化
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(transformView:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

//鍵盤迴收
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    for(UIView *view in self.view.subviews)
    {
        [view resignFirstResponder];
    }
}

//移動UIView
-(void)transformView:(NSNotification *)aNSNotification
{
    //獲取鍵盤彈出前的Rect
    NSValue *keyBoardBeginBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect beginRect=[keyBoardBeginBounds CGRectValue];
    
    //獲取鍵盤彈出後的Rect
    NSValue *keyBoardEndBounds=[[aNSNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect  endRect=[keyBoardEndBounds CGRectValue];
    
    //獲取鍵盤位置變化先後縱座標Y的變化值
    CGFloat deltaY=endRect.origin.y - beginRect.origin.y;
    NSLog(@"看看這個變化的Y值:%f",deltaY);
    
    //在0.25s內完成self.view的Frame的變化,等因而給self.view添加一個向上移動deltaY的動畫
    [UIView animateWithDuration:0.25f animations:^{
        [self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y+deltaY, self.view.frame.size.width, self.view.frame.size.height)];
    }];
}
相關文章
相關標籤/搜索