【发布时间】:2014-12-02 09:29:37
【问题描述】:
我知道这个问题被问了很多次,但我不知道我在哪里犯错了。简而言之,我无法正确实施它。
我的应用程序必须在 iPhone 和 iPad 上运行(仅限纵向)。我有一个子类UITextField。当它在编辑过程中被键盘隐藏时,我需要将它向上移动。
我无法正确设置它,因为键盘大小的计算是在它进入编辑模式后完成的。
我知道我需要以下步骤:
- 注册观察者
- 具有计算键盘矩形的例程,我可以从中获取高度
- 在键盘的显示和隐藏上有 2 个事件来偏移我的自定义文本字段。
请告诉我哪里错了。
我的代码是:
注册观察者:
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardDidShowNotification object:nil];
_leftInlineImage = NO;
}
return self;
}
计算键盘高度:
- (void)keyboardWillChange:(NSNotification *)notification {
NSDictionary* d = [notification userInfo];
CGRect r = [d[UIKeyboardFrameEndUserInfoKey] CGRectValue];
r = [self.superview convertRect:r fromView:nil];
_keyboardHeight = r.size.height;
}
显示/隐藏键盘:
/* Move keyboard */
-(void)showKeyboardWithMove {
CGRect screenRect = [[UIScreen mainScreen] bounds];
////CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
//_keyboardHeight = KEYBOARD_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];
}
}
-(void)hideKeyboardWithMove {
CGRect rect = CGRectMake(0, 0, 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];
}
之前计算过,我的身高是0。这一切都是在UITextField的子类中完成的。
【问题讨论】:
-
我知道这是重复的@Chan,但我无法实现它,这就是我问这个问题的原因。
-
但是为了让键盘出现,一个可编辑的 UI 元素需要获得焦点。所以我不明白为什么会出现混乱?
-
我很抱歉@Lefteris,但我不明白你的话。当然首先文本字段必须获得焦点。我的问题是当它获得焦点时
showKeyboardWithMove被调用,然后keyboardWillChange,这导致键盘高度= 0,即我什么都不做。
标签: ios objective-c