【发布时间】:2016-04-06 07:17:24
【问题描述】:
如果键盘出现,我想让我的视图自动向上移动。已经使用苹果的代码here 并且效果很好。
这就是我管理对象的方式,因此我创建了一个覆盖UIView 的UIScrollView。这个UIView 由UITextField 和UIButton 组成。
这是我在键盘出现时调整视图的方式。
#pragma mark - Keyboard Handling
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
_scrollView.contentInset = contentInsets;
_scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, _mainView.frame.origin) ) {
[self.scrollView scrollRectToVisible:_mainView.frame animated:YES];
}
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
_scrollView.contentInset = contentInsets;
_scrollView.scrollIndicatorInsets = contentInsets;
}
但我认为有一点让这很奇怪。当键盘出现时,它会滚动并且我的UITextField 变得可见。但是我觉得太紧了。
在我看来,如果我的UITextField 向上移动一点会更好。我的问题是,如何设置它的滚动可见性?看起来应该在这里添加一些变量和一些常量
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, _mainView.frame.origin) ) {
[self.scrollView scrollRectToVisible:_mainView.frame animated:YES];
}
非常感谢您,我们将不胜感激。
【问题讨论】:
标签: ios objective-c uiview uiscrollview