iOS 根據鍵盤的高度動態改變UIView的高度


在我們使用鍵盤時常常出現鍵盤擋着視圖這種情況,下面我給大家介紹一種方法可以根據鍵盤的高度來動態改變視圖的度使其可以始終在鍵盤的上邊

在這里視圖我用TextView

UIKeyboardWillShowNotification//鍵盤彈出
UIKeyboardWillHideNotification//鍵盤縮回
   //用通知監聽鍵盤的彈出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboarShow:) name:UIKeyboardWillShowNotification object:nil];
   
   //監聽鍵盤的縮回
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHiden:) name:UIKeyboardWillHideNotification object:nil];
   
    //設置delegate
    _myTextView.delegate=self;
   

    // Do any additional setup after loading the view, typically from a nib.
}
//顯示
-(void)keyboarShow:(NSNotification *)notification{
   //獲取鍵盤的高度
    CGRect rect =[notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
   //計算出 textView的height
    CGRect textViewRect=_myTextView.frame;
     CGFloat height=textViewRect.size.height-rect.size.height;
    textViewRect.size.height=height;
    [UIView animateWithDuration:.2 animations:^{
        self.myTextView.frame=textViewRect;
    }];
}
//鍵盤隱藏時調用
-(void)keyBoardHiden:(NSNotification *)notification{
    _myTextView.frame=self.view.frame;
}
 
這樣就可以達到我們想要的效果了  如果有什么問題可以提問哦。大家一起學習


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM