我有UITextField
的子類。我想知道鍵盤何時可見。如果鍵盤隱藏我的文本字段,這將幫助我移動所有視圖。如何在UITextField子類中正確添加addObserver以便在鍵盤可見時進行獲取?
在我的子類,我想補充觀察員如下:
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardIsVisible:) name:UIKeyboardDidShowNotification object:nil];
}
return self;
}
我希望能趕上鍵盤的大小:
/* Get height when keyboard is visible */
- (void)keyboardIsVisible:(NSNotification*)notification
{
NSDictionary* keyboardInfo = [notification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
_keyboardHeight =keyboardFrameBeginRect.size.height;
}
我會用伊娃_keyboardHeight
來決定,如果我有移動鍵盤:
/* Move keyboard */
-(void)showKeyboardWithMove {
CGRect screenRect = [[UIScreen mainScreen] bounds];
////CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
if (self.frame.origin.y + self.frame.size.height > screenHeight - _keyboardHeight) {
double offset = screenHeight - _keyboardHeight - self.frame.origin.y - self.frame.size.height;
CGRect rect = CGRectMake(0, offset, self.superview.frame.size.width, self.superview.frame.size.height);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
self.superview.frame = rect;
[UIView commitAnimations];
}
}
從我的視圖控制器類我呼籲showKeyboardWithMove
:
- (void)textFieldDidBeginEditing:(MyCustomTextField *)textField
{
// Call method for moving control when Keyboard is shown and hides it
[textField showKeyboardWithMove];
}
- (void)textFieldDidEndEditing:(MyCustomTextField *)textField
{
// Call method for returning control when Keyboard is hidden
[textField hideKeyboardWithMove];
}
問題是,當我第一次顯示鍵盤時,keyboardIsVisible
不起火。所以我認爲我的觀察員沒有正確編碼。有任何想法嗎?
的可能的複製[如何使一個的UITextField向上移動時,鍵盤的存在(http://stackoverflow.com/questions/1126726/how-to-make-a-uitextfield-move-up-when -keyboard-is-present) – PAC 2016-02-16 07:20:27