使用autolayout配置UIScrollView内容,使用键盘插入和旋转到横向

pai*_*aiv 9 landscape uiscrollview ios autolayout

我正在与autolayout(iOS 6,7)中的scrollview进行一段时间的斗争,而且它正在变得令人沮丧.

考虑一个简单的报名表

我想要滚动,这应该在横向调整大小:

肖像

视图层次结构是:

查看层次结构

我需要配置适当的约束以便

  • 当键盘出现并消失时,滚动区域会正确更新
  • 当设备旋转到横向并返回到纵向时,内容会调整大小
  • 滚动区域适当地更新了横向和纵向

这可以在没有代码的情况下完成吗?

我得到了什么

键盘出现时滚动尺寸错误

错误的滚动大小

内容未在横向上调整大小

没有在景观中调整大小

要使用的源代码:

源代码

Jon*_*man 9

看哪!经过2天的搜索,我相信我可能会有一个答案.诚然,没有代码就无法完成.

首先从contentView到Scroll视图创建常用的top,bottom,leading和trailing约束.但是使用前导和尾随,勾选"占位符 - 在构建时删除"选项.

然后在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];
Run Code Online (Sandbox Code Playgroud)

这会动态地将contentView中的前导和尾随约束添加到控制器的主视图(即滚动视图之外).

然后,当您旋转设备时,输入字段将被适当拉伸.这解决了你的旋转问题,关于键盘出现在SO上的其他答案,但基本上在viewDidLoad内:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardDidHideNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

然后添加以下两种方法:

- (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;
}
Run Code Online (Sandbox Code Playgroud)

  • 作为添加约束以将contentView的左/右绑定到外部视图的替代方法,可以在Interface Builder中将contentView和主视图的宽度设置为相等.请参阅:http://natashatherobot.com/ios-autolayout-scrollview/ (2认同)