使用UIScrollView的正确方法是什么?

时间:2015-02-05 11:21:11

标签: ios objective-c xcode xib

我尝试设置一个简单的视图,该视图显示带有标题的纯文字文章。以下是我已经完成的步骤:

  1. 使用.xib文件创建View Controller,
  2. 创建UIScrollView并直接将UIView作为内容包装器
  3. 在顶部,底部,前导和尾随中设置约束[scrollview]-0-[superview]
  4. 在顶部,底部,前导和尾随中设置约束[content wrapper]-0-[scroll view]
  5. 将内容包装器的宽度和高度设置为占位符。
  6. LabelUITextView添加为内容包装器的子视图。
  7. 为子视图添加约束。
  8. 关注this tutorial,我以编程方式设置内容包装器的leading = scrollview的超级视图,
  9. ...内容包装器的尾随= scrollview的超级视图权。
  10. 当我运行代码时,它完美地显示了所有内容; UIScrollView滚动,边距设置正确等等。

    然而,Xcode抛出异常:

    2015-02-05 18:06:58.230 ScrollViewApp[5353:180401] Unable to simultaneously satisfy constraints.
        Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
    (
        "<NSLayoutConstraint:0x7ff9fa49a3f0 H:[UIView:0x7ff9fa571560(600)]>",
        "<NSLayoutConstraint:0x7ff9fa49b1a0 H:|-(0)-[UIView:0x7ff9fa571560]   (Names: '|':UIScrollView:0x7ff9fa49a910 )>",
        "<NSLayoutConstraint:0x7ff9fa49ce00 H:|-(0)-[UIScrollView:0x7ff9fa49a910]   (Names: '|':UIView:0x7ff9fa49a840 )>",
        "<NSLayoutConstraint:0x7ff9fa61c050 UIView:0x7ff9fa571560.right == UIView:0x7ff9fa49a840.trailing>",
        "<NSLayoutConstraint:0x7ff9fa580970 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7ff9fa49a840(375)]>"
    )
    
    Will attempt to recover by breaking constraint 
    <NSLayoutConstraint:0x7ff9fa49a3f0 H:[UIView:0x7ff9fa571560(600)]>
    
    Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
    The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
    

    进一步谷歌搜索后,我发现我可以通过将内容包装器的宽度(参见上面的步骤5)优先级设置为低来解除警告;但它打破了界面构建器中的布局。看看:

    Content wrapper's width constraint set to low priority

    与设置为高优先级时相比:

    Content wrapper's width constraint set to HIGH priority

    我知道最终它没有任何区别,因为它都按预期工作。但我有点好奇为什么会发生这些事情..

    我试图了解UIScrollView的工作原理,但也许我误解了一些东西;那么,设置UIScrollView按预期工作的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

尝试从内容包装器向滚动视图添加中心水平约束。 说实话,我真的不知道为什么会这样,我通过审判认出这个错误。如果希望视图与不同的屏幕大小兼容,请删除内容包装器的宽度约束。 希望它有所帮助。

答案 1 :(得分:0)

你可以像这样使用scrollview。在设计中添加scrollview。在设计中给出左,上,右,下限制。在scrollview中添加子视图。为它们添加适当的约束。无需在代码中添加约束。在viewDidLayoutSubviews中设置您的scrollview的内容大小。 - (void)viewDidLayoutSubviews {

[super viewDidLayoutSubviews];
CGRect boundsOfSelf = self.view.bounds;
scrollView.frame = boundsOfSelf;
[scrollView setContentSize: boundsOfSelf.size];

}