[英]Trouble with scrollview
我对ScrollView有一个奇怪的问题。 我目前在一个ViewController上有4个TextField和4个Label,当键盘弹出时,它会阻塞4对TextField和Label中的3对的视图。 我添加了ScrollView,但是当我这样做时,突然无法单击TextFields并弹出键盘。 有什么想法或替代方法来解决视力障碍吗?
听起来您只是在所有标签和文本字段的顶部放置了一个滚动视图。 您需要将所有文本字段和标签添加为滚动视图的子视图,应将它们拖入其中。 您必须设置适当的约束,并使滚动视图具有基于其内容的正确内容大小。 然后,您需要更新约束,这些约束会在出现或关闭键盘时影响滚动视图的内容大小,而不仅仅是自动工作。
您可能在文本字段顶部具有新视图,因此单击时实际上是在视图中单击,而不是在文本字段中。 这很容易在XCode的调试视图中看到。 关于键盘覆盖测试区域的问题,要解决此问题,您必须分配给这两个通知
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
并实现代码以在键盘弹出时将您的字段移开,并在键盘消失时将其移回正常位置。 就像是:
-(void)keyboardWillShow {
// Animate the current view out of the way
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}
-(void)keyboardWillHide {
if (self.view.frame.origin.y >= 0)
{
[self setViewMovedUp:YES];
}
else if (self.view.frame.origin.y < 0)
{
[self setViewMovedUp:NO];
}
}
关于它的文章很多,一个很好的例子是“如何在有键盘的情况下使UITextField向上移动”如何在有键盘的情况下使UITextField向上移动?
希望对您有所帮助。
首先,您必须在UIScrollView 内添加所有UITextField和UILabel:
[self.scrollView addSubView:textField1];
[self.scrollView addSubView:label1];
[self.scrollView addSubView:textField2];
[self.scrollView addSubView:label1];
// ...
然后,不要忘记设置您的scrollView frame
(通常在initWithFrame
或更佳的layoutSubviews
)。 您还需要设置您的scrollView的contentSize
属性。 这表示该scrollView中的内容有多大。
self.scrollView.frame = self.view.bounds;
self.scrollView.contentSize = self.view.bounds.size;
在您的viewDidAppear
,注册键盘通知:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardWillHideNotification object:nil];
在viewWillDisappear
取消注册这些通知:
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
最后,实现您注册通知时作为选择器提供的那些keyboardWillShowNotification:
和keyboardWillHideNotification:
::
- (void)keyboardWillShowNotification:(NSNotification *)notification {
CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIEdgeInsets insets = self.scrollView.contentInset;
insets.bottom = keyboardFrame.size.height;
self.scrollView.contentInset = insets;
}
- (void)keyboardWillHideNotification:(NSNotification *)notification {
self.scrollView.contentInset = UIEdgeInsetsZero;
}
这样,当显示键盘时,您将能够使UIScrollView滚动以显示所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.