問題描述: ? 針對APP界面登錄和注冊時芜繁,有時要求密碼輸入格式特殊旺隙,并且輸入的標識符要時刻顯示,并針對鍵盤遮擋部分自適應上移骏令。
舉例說明:類似下面界面怎樣實現
1蔬捷,進入界面,鍵盤擋住輸入界面榔袋;解決此問題周拐,本人用的方法:用ScrollVIew做背景面,UIView做content視圖凰兑,遮擋與重疊部分用OC自帶方法CGRectIntersection妥粟、CGRectUnion算出,進行ScrollView的contentInset重置吏够。
此時關鍵不要忘記ScollView的contentSize相等于contentView的frame.size:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
self.scrollView.contentSize = self.contentView.frame.size;
}
核心代碼:注冊兩個通知中心勾给,對UIKeyboardDidShowNotification、UIKeyboardDidHideNotification進行相關處理锅知,當dealloc是要銷毀通知以提高app效率
- (void)registerForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardDidHideNotification object:nil];
}
- (void)unregisterForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
難點在于處理相交部分并且順應上移播急,看代碼:
- (void)keyboardDidShow:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
CGRect keyboardEndFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGRect overlappedRect = CGRectIntersection(self.scrollView.bounds, [self.view.window convertRect:keyboardEndFrame toView:self.scrollView]);
CGSize kbSize = overlappedRect.size;
UIEdgeInsets contentInsets = self.scrollView.contentInset;
contentInsets.bottom = kbSize.height;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
[self scrollInputViewsToVisible];
}
- (void)keyboardWillHide:(NSNotification*)notification {
NSDictionary* info = [notification userInfo];
CGRect keyboardBeginFrame = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect overlappedRect = CGRectIntersection(self.scrollView.bounds, [self.view.window convertRect:keyboardBeginFrame toView:self.scrollView]);
CGSize kbSize = overlappedRect.size;
UIEdgeInsets contentInsets = self.scrollView.contentInset;
contentInsets.bottom -= kbSize.height;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
將重疊部分移到可見處,發(fā)放如下:
- (void)scrollInputViewsToVisible {
CGRect visibleRect = CGRectUnion(self.userTextField.frame, self.inputView.frame);
visibleRect = [self.scrollView convertRect:visibleRect fromView:self.contentView];
[self.scrollView scrollRectToVisible:visibleRect animated:YES];
}
鍵盤自適應已經解決售睹!
2桩警,對自帶鍵盤消除鍵自定義:
此時不難想到我們要創(chuàng)建繼承于UITextField的類,并遵循<UIKeyInput>侣姆,再對方法- (void)deleteBackward進行重寫生真,如下:
- (void)deleteBackward {
BOOL textWasEmpty = ![self.text length];
[super deleteBackward];
if (textWasEmpty && [_myDelegate respondsToSelector:@selector(textFieldDidDeleteWhenEmpty:)]) {
[_myDelegate textFieldDidDeleteWhenEmpty:self];
}}
詳細代碼可參照我做的Demo: