我們在開發過程中經常會遇到一個問題是,當我們選擇輸入框時會有鍵盤跳出覆蓋了我們的輸入框,這個時候我們需要解決的問題就是:將我們的輸入框上移,使它先是在鍵盤上方:
前提:
在您的h檔案中聲明一個textfield
@property (retain, nonatomic) IBOutlet UITextField *textView;
首先在viewDIdLoad方法中如下:
- (void)viewDidLoad{ [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwasShown:) name:UIKeyboardDidShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardwasHidden:) name:UIKeyboardDidHideNotification object:nil];}
這個方法裡我們調用了兩個方法,一個是鍵盤顯示時的偵聽事件的處理,另一個是鍵盤消失時的偵聽事件的處理。
(1)鍵盤顯示時的偵聽事件的處理
-(void)keyboardwasShown:(NSNotification *) notify{ CGRect frame = [self.view frame]; if ([[notify name]isEqualToString:UIKeyboardDidShowNotification]) { [UIView animateWithDuration:0.3 animations:^{ self.view.frame = frame; }completion:^(BOOL finished) { // }]; } NSDictionary *info = [notify userInfo]; NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey]; CGSize keyBoardSize = [aValue CGRectValue].size; CGRect rect = self.textView.frame; rect.origin.y = self.view.frame.size.height - keyBoardSize.height - rect.size.height; self.textView.frame = rect; }
(2)鍵盤消失時的偵聽事件的處理
-(void) keyboardwasHidden:(NSNotification *) notify{ NSDictionary *info = [notify userInfo]; NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey]; CGSize keyBoardSize = [aValue CGRectValue].size; CGRect rect = self.textView.frame; rect.origin.y = self.view.frame.size.height - rect.size.height; self.textView.frame = rect;}