在iOS中衬浑,點擊textfield控件會彈出系統(tǒng)鍵盤昔脯,如果鍵盤位置在下方啄糙,那么會出現(xiàn)該控件被鍵盤遮擋的情況,這時候就需要讓textfield的位置隨著鍵盤彈出而變換云稚。研究了一下關(guān)鍵代碼如下隧饼。
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
- (void)keyBoardDidShow:(NSNotification *)notif {
NSLog(@"===keyboar showed====");
if (keyboardDidShow) return;
// get keyboard size
NSDictionary *info = [notif userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
// reset scrollview frame
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height -= keyboardSize.height;
self.scrollView.frame = viewFrame;
// scroll to current textfiled
CGRect textfieldRect = [self.textfield frame];
[self.scrollView scrollRectToVisible:textfieldRect animated:YES];
keyboardDidShow = YES;
}
- (void)keyBoardDidHide:(NSNotification *)notif {
NSLog(@"====keyboard hidden====");
NSDictionary *info = [notif userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height += keyboardSize.height;
self.scrollView.frame = viewFrame;
if (!keyboardDidShow) {
return;
}
keyboardDidShow = NO;
}
@end
對代碼的解釋:
UIKeyboardDidShowNotification,UIKeyboardDidHideNotification分別是鍵盤出現(xiàn)和鍵盤消失的通知静陈。將ScrollView滾動到textfield控件燕雁,通過scrollRectToVisible:animated:
來實現(xiàn)诞丽,其中scrollRectToVisible參數(shù)用于指定滾動到一個矩形區(qū)域,文檔中解釋為:Scrolls a specific area of the content so that it is visible in the receiver.這個矩形區(qū)域是CGRect結(jié)構(gòu)體拐格。每個視圖的frame方法可以獲得CGRrect結(jié)構(gòu)體數(shù)據(jù)僧免。