大家早上好/晚上好。我试图这样做,当键盘出现时,文本字段和整个视图向上移动。我正在使用一些NSNotificationCenter
代码来查找屏幕上的键盘(UIKeyboardDidShowNotification
)。
调用此方法没有问题,然后它正确地更改视图。但是第一次和第一次调用它时,视图将重置为默认值,而不是新值。
然后,第二次,第三次等等,它完美无缺。我怎样才能解决这个问题?
ViewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardOnScreen:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardOffScreen:) name:UIKeyboardDidHideNotification object:nil];
方法:
-(void)keyboardOnScreen:(NSNotification *)notification
{
NSDictionary *info = notification.userInfo;
NSValue *value = info[UIKeyboardFrameEndUserInfoKey];
CGRect rawFrame = [value CGRectValue];
CGRect keyboardFrame = [self.view convertRect:rawFrame fromView:nil];
double y = keyboardFrame.size.height;
if (y == 0) {
NSLog(@"prevented error!");
} else {
NSLog(@"%f", y);
CGRect frame = [input frame];
double nonorigil = origianltexty - y;
frame.origin.x = originaltextx;
frame.origin.y = nonorigil;
[input setFrame:frame];
CGRect fra = [scrollView frame];
CGRect screenBound = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBound.size;
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
fra.size.height = (screenHeight - y) - 60;
[scrollView setFrame:fra];
CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height);
[scrollView setContentOffset:bottomOffset animated:NO];
}
}
-(void) keyboardOffScreen: (NSNotification *)notification {
NSLog(@"keyboard went away");
}
当"发送"按下按钮......
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
input.text = @"";
CGRect frame = [input frame];
frame.origin.x = originaltextx;
frame.origin.y = origianltexty;
[input setFrame:frame];
[textField resignFirstResponder];
return NO;
}
答案 0 :(得分:0)
我最终通过使用自动布局和更改约束来克服这一点,而不是通知委托函数中的帧大小或位置,如下所示:
P.S。我没有使用scrollview只是简单的移动视图,但它应该工作类似
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if !keyboardIsShown{
self.infoViewTopConstraint.constant -= keyboardSize.height
self.infoViewBottomConstraint.constant += keyboardSize.height
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
keyboardIsShown = true
}
}
}
func keyboardWillHide(notification: NSNotification) {
if keyboardIsShown {
self.infoViewTopConstraint.constant += keyboardSize.height
self.infoViewBottomConstraint.constant -= keyboardSize.height
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
keyboardIsShown = false
}
}