標籤:
此文為轉載。僅供收藏
//收到鍵盤彈出通知後的響應
- (void)keyboardWillShow:(NSNotification *)info {
//儲存info
NSDictionary *dict = info.userInfo;
//得到鍵盤的顯示完成後的frame
CGRect keyboardBounds = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//得到鍵盤彈齣動畫的時間
double duration = [dict[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//座標系轉換
//由於取出的位置資訊是絕對的,所以要將其轉換為對應於當前view的位置,否則位置資訊會出錯!
CGRect keyboardBoundsRect = [self.view convertRect:keyboardBounds toView:nil];
//得到鍵盤的高度,即輸入框需要移動的距離
double offsetY = keyboardBoundsRect.size.height;
//得到鍵盤動畫的曲線資訊,按原作的話說“此處是痛點”,stackoverflow網站裡找到的
UIViewAnimationOptions options = [dict[UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16;
//添加動畫
[UIView animateWithDuration:duration delay:0 options:options animations:^{
_textField.transform = CGAffineTransformMakeTranslation(0, -offsetY);
} completion:nil];
}
//隱藏鍵盤通知的響應
- (void)keyboardWillHide:(NSNotification *)info {
//輸入框回去的時候就不需要高度了,直接取動畫時間和曲線還原回去
NSDictionary *dict = info.userInfo;
double duration = [dict[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
UIViewAnimationOptions options = [dict[UIKeyboardAnimationCurveUserInfoKey] integerValue] << 16;
//CGAffineTransformIdentity是置位,可將改變的transform還原
[UIView animateWithDuration:duration delay:0 options:options animations:^{
_textField.transform = CGAffineTransformIdentity;
} completion:nil];
}
擷取鍵盤移動動畫,製作控制項跟隨特效。