2013年6月18日 星期二

如何解決 Keyboard 擋住 TextField 的問題?


Beginning...



按下任一欄位,準備輸入文字時...




如何解決 Keyboard 擋住 TextField 的問題呢?


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //指定 TextField 將使用其 delegate
    self.nameField.delegate = self;
    self.numberField.delegate = self;
    
    //向 NotificationCenter 申請註冊,在 UIKeyboardDidShowNotification 時,
    //會呼叫 keyboardDidShow (自訂的) 這個 selector。
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    //向 NotificationCenter 申請註冊,在 UIKeyboardWillHideNotification 時,
    //會呼叫 keyboardWillHide (自訂的) 這個 selector。
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

-(void) keyboardDidShow: (NSNotification *) notification {
    
    //取得鍵盤高度
    NSValue * value = [[notification userInfo] valueForKey:UIKeyboardFrameBeginUserInfoKey];
    CGFloat keyboardHeight = [value CGRectValue].size.height;
    //以動畫的方式,將 View 的 Y軸 往上移一個鍵盤高
    [UIView animateWithDuration:0.3f animations:^
     {
         CGRect frame = self.view.frame;
         frame.origin.y -= keyboardHeight;
         self.view.frame = frame;
     }
     ];
}

-(void) keyboardWillHide: (NSNotification *) notification {
    
    NSValue * value = [[notification userInfo] valueForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardHeight = [value CGRectValue].size.height;
    
    [UIView animateWithDuration:0.3f animations:^
     {
         CGRect frame = self.view.frame;
         frame.origin.y += keyboardHeight;
         self.view.frame = frame;
     }
     ];
}


最後記得,註冊過的 Observer 要 release 掉

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
    //只要有向 Notification Center 申請註冊,要記得 remove 掉
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}