[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotificationobject:nil];
[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotificationobject:nil];
在dealloc中,注销这两个通知:
[[NSNotificationCenter defaultCenter] removeObserver:selfname:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:selfname:UIKeyboardWillHideNotification object:nil];
3. 通知响应函数 的定义以及实现。
假设 输入框为
UITextField * m_inputField; - (void)keyboardWillShow:(NSNotification *)aNotification; - (void)keyboardWillHide:(NSNotification *)aNotification; - (void)keyboardWillShow:(NSNotification *)aNotification {if ([m_inputField isFirstResponder] == NO)
{ return; } CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect bottomframe = m_bottomImage.frame; bottomframe.origin.y -= keyboardRect.size.width - m_curKeyboardHeight; CGRect fieldframe = m_inputField.frame; fieldframe.origin.y -= keyboardRect.size.width - m_curKeyboardHeight;[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration]; m_bottomImage.frame = bottomframe; m_inputField.frame = fieldframe;[UIView commitAnimations];
m_curKeyboardHeight = keyboardRect.size.width; } - (void)keyboardWillHide:(NSNotification *)aNotification {if ([m_inputField isFirstResponder] == NO)
{ return; }NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
CGRect bottomframe = m_bottomImage.frame; bottomframe.origin.y += m_curKeyboardHeight; CGRect fieldframe = m_inputField.frame; fieldframe.origin.y+= m_curKeyboardHeight;[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration]; m_bottomImage.frame = bottomframe; m_inputField.frame = fieldframe;[UIView commitAnimations];
m_curKeyboardHeight = 0;
} ]]>
评论区