我在自动布局 (iOS 6,7) 中与 ScrollView 作斗争已经有一段时间了,而且越来越令人沮丧。
考虑一个简单的条目表单
我希望它是可滚动的,并且应该在横向上调整大小:
View 层次结构是:
我需要配置适当的约束,以便
- 滚动区域在键盘出现和消失时正确更新
- 当设备旋转到横向并返回纵向时,内容会调整大小
- 滚动区域针对横向和纵向适当更新
这可以不用代码完成吗?
我得到的是什么
出现键盘时滚动尺寸错误
横向内容未调整大小
可使用的源代码:
最佳答案
看哪!经过 2 天的搜索,我相信我可能会有答案。不可否认,没有代码就无法完成。
首先创建从 contentView 到 ScrollView 的常规顶部、底部、前导和尾随约束。 但是对于前导和尾随,请勾选“占位符 - 在构建时删除”选项。
然后在您的 viewDidLoad 方法中添加以下内容:
NSLayoutConstraint *leftConstraint =[NSLayoutConstraint
constraintWithItem:self.contentView
attribute:NSLayoutAttributeLeading
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeLeft
multiplier:1.0
constant:0];
[self.view addConstraint:leftConstraint];
NSLayoutConstraint *rightConstraint =[NSLayoutConstraint
constraintWithItem:self.contentView
attribute:NSLayoutAttributeTrailing
relatedBy:0
toItem:self.view
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:0];
[self.view addConstraint:rightConstraint];
这会动态地将前导和尾随约束从您的 contentView 添加到 Controller 的主视图(即在 ScrollView 之外)。
然后,当您旋转设备时,输入字段会适当拉伸(stretch)。 这解决了您的旋转问题,关于出现的键盘还有其他答案,但基本上在 viewDidLoad 内部:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardDidHideNotification object:nil];
然后添加这两个方法:
- (void) keyboardWasShown:(NSNotification *)notification
{
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
- (void) keyboardWillBeHidden:(NSNotification *)notification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
关于ios - 使用自动布局、键盘插入和横向旋转配置 UIScrollView 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19691882/