標籤:
一、鍵盤通知
我們經常需要在鍵盤彈出或者隱藏的時候做一些特定的操作,因此需要監聽鍵盤的狀態
鍵盤狀態改變的時候,系統會發出一些特定的通知
UIKeyboardWillShowNotification // 鍵盤即將顯示
UIKeyboardDidShowNotification // 鍵盤顯示完畢
UIKeyboardWillHideNotification // 鍵盤即將隱藏
UIKeyboardDidHideNotification // 鍵盤隱藏完畢
UIKeyboardWillChangeFrameNotification // 鍵盤的位置尺寸即將發生改變
UIKeyboardDidChangeFrameNotification // 鍵盤的位置尺寸改變完畢
系統發出鍵盤通知時,會附帶一下跟鍵盤有關的額外資訊(字典),字典常見的key如下:
UIKeyboardFrameBeginUserInfoKey // 鍵盤剛開始的frame
UIKeyboardFrameEndUserInfoKey // 鍵盤最終的frame(動畫執行完畢後)
UIKeyboardAnimationDurationUserInfoKey // 鍵盤動畫的時間
UIKeyboardAnimationCurveUserInfoKey // 鍵盤動畫的執行節奏(快慢)
點擊Text Field彈出文字時 讓Text Field始終跟著鍵盤移動,並且貼著鍵盤上面
正因為鍵盤狀態改變的時候,系統會發出一些特定的通知,我們可以監聽鍵盤的狀態
- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];}- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self];}
實現方法:
/** * 監聽鍵盤的frame即將發生改變的時候調用 */- (void)keyboardWillChange:(NSNotification *)note{ // 獲得鍵盤最後的frame CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; // 修改底部約束 self.bottomSpace.constant = self.view.frame.size.height - frame.origin.y; // 執行動畫 CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; [UIView animateWithDuration:duration animations:^{ [self.view layoutIfNeeded]; }];} // 觸控螢幕幕退出鍵盤- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ // 文字框不再是第一響應者,就會退出鍵盤// [self.textField resignFirstResponder]; // [self.textField endEditing:YES]; [self.view endEditing:YES];}
userInfo是系統提供的字典屬性
@property (nullable, readonly, copy) NSDictionary *userInfo;
列印的結果如下:
UIKeyboardAnimationCurveUserInfoKey = 7; // 動畫曲線動畫
UIKeyboardAnimationDurationUserInfoKey = "0.25"; // 動畫時間
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 253}}"; // 鍵盤bounds
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 694.5}"; // 開始鍵盤的置中位置
UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 441.5}"; // 結束鍵盤的置中位置
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 568}, {320, 253}}";// 鍵盤開始彈出的frame
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 315}, {320, 253}}";// 退出鍵盤的frame
UIKeyboardIsLocalUserInfoKey = 1;
IOS開發——UI進階篇(六)鍵盤處理