iOS 老生常談的鍵盤遮擋問題
一、如果在tableview內,可以採用tableview偏移來解決:
– (void)textFieldDidBeginEditing:(UITextField *)textField{
if ([textField isEqual:XXXX]) {
CGPoint origin = textField.frame.origin;
CGPoint point = [textField.superview convertPoint:origin toView:self.tableView];
float navBarHeight = self.navigationController.navigationBar.frame.size.height;
CGPoint offset = self.tableView.contentOffset;
// change offsetY
offset.y = (point.y – 216 – navBarHeight-40);//216固定鍵盤高度,雖然不精准但勉強可以用
[self.tableView setContentOffset:offset animated:YES];
}
}
二、比較通用的遮擋處理,利用內置UIKeyboard通知
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];//鍵盤彈出
[center addObserver:self selector:@selector(keyboardDidHide) name:UIKeyboardWillHideNotification object:nil]; //鍵盤收起
– (void)keyboardWillShow:(NSNotification *)aNotification{
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
CGFloat _keyboardHeight = ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) ? keyboardRect.size.height : keyboardRect.size.width;//獲取到鍵盤高度
//接下來想怎麼做都可以,改變ViewOffset、Frame等等 然後在keyboardHide事件中還原就可以
//示例:
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0.0f, -1 * _keyboardHeight, self.view.frame.size.width, self.view.frame.size.height);
}];
}
发表评论或回复