新項目中市殷,有一個頁面大部分都是TextField輸入框愕撰,并且已經超過了一屏,填寫內容時醋寝,鍵盤容易擋住輸入框搞挣,很是煩人,研究了好久音羞,找出了一個較為滿意的方法囱桨,貼出來,大家可以一起看看
我的頁面整體是一個scrollview,上面貼了一些view,view上面貼著textfield.
分析: 個人覺得嗅绰,應該在鍵盤彈起的時候舍肠,測量當前textfield在屏幕中的位置,current_y,及current_height窘面,計算當前鍵盤的height是否比當前textfield的下方位置要高翠语,如果高的話,則需調整self.view整體位置财边。上代碼:
#import "NewDocuView.h"
#define INTERVAL_KEYBOARD 50.0/H_BASE*SCREEN_H //自定義鍵盤的緩沖距離
@property (nonatomic,assign)float currentf_heihgt; //當前tf的高度
@property (nonatomic,assign)float currentf_y;? //當前tf的y值肌括,方便獲得keyborard移動位置計算
?1.監(jiān)聽keyboard的彈起和隱藏
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[defaultCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
2.獲得當前輸入框所在的位置
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//獲得控件相對于屏幕的位置,不管控件被包含在哪個視圖中酣难。们童。return YES;
UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
CGRect rect=[textField convertRect: textField.bounds toView:window];
_currentf_y = rect.origin.y;
_currentf_heihgt? = textField.frame.size.height;
}
3.鍵盤的代理方法
#pragma mark? - - - --? 監(jiān)聽,鍵盤顯示獲得鍵盤的高度 - - - - -- - - -
- (void)keyboardWillShow:(NSNotification *)aNotification
{
//獲取鍵盤的高度
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
keyboardheight = keyboardRect.size.height;
//計算出鍵盤頂端到inputTextView panel底端的距離(加上自定義的緩沖距離INTERVAL_KEYBOARD)
//如果大于0鲸鹦,則鍵盤將輸入框遮擋慧库,需調節(jié)高度,小于0馋嗜,則不需要調節(jié)
//SCREEN_H 為屏幕高度
CGFloat offset = _currentf_y + _currentf_heihgt + INTERVAL_KEYBOARD - (SCREEN_H - keyboard height);
//取得鍵盤的動畫時間齐板,這樣可以在視圖上移的時候更連貫
double duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//將視圖上移計算好的偏移
if(offset > 0) {
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
}];
}
#pragma mark? - - - --? 監(jiān)聽,鍵盤消失時 - - - - -- - - -
- (void) keyboardWillHide:(NSNotification *)notify {
NSLog(@"key hidden");
// 鍵盤動畫時間
double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//視圖下沉恢復原狀
[UIView animateWithDuration:duration animations:^{
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}];
}