自动布局的UIScrollView内容大小问题

时间:2016-06-25 02:32:21

标签: ios swift uiscrollview autolayout

当我向UIScrollView添加多个子视图时,ScrollView的contentsSize不会自动更改(正如指南建议的那样)。

如果我将contentsSize设置为宽度的6倍(我正在制作6页滚动视图),则视图会正确布局。但是我没有手动设置contentsSize,滚动视图不会滚动而contentsSize(0,0)

显而易见的答案是只需手动设置contentSize,但我很紧张,我有一个更基本的问题(或对自动布局的误解),这将在以后伤害我。我的代码如下:

 override func viewDidLoad() {
    super.viewDidLoad()

    //Adding a Paging ScrollView to ViewController
    let sv = UIScrollView() 
    view.addSubview(sv)
    sv.pagingEnabled = true

    let allC1 = NSLayoutConstraint.constraintsWithVisualFormat("H:|[sv]|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["sv": sv])
    let allC2 = NSLayoutConstraint.constraintsWithVisualFormat("V:|[sv]|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["sv": sv])
    NSLayoutConstraint.activateConstraints(allC1+allC2)

    sv.translatesAutoresizingMaskIntoConstraints = false

    var subViewConstraints:[NSLayoutConstraint] = []
    var mySubViews:[UIView] = []

    //First SubView Add & Layout
    let firstView = UIView(withIndex: 0)
    mySubViews.append(firstView)
    sv.addSubview(firstView)
    let cWidth = NSLayoutConstraint(item: tempView, attribute: .Width, relatedBy: .Equal, toItem: sv, attribute: .Width, multiplier: 1.0, constant: 0.0)
    let cHeight = NSLayoutConstraint(item: tempView, attribute: .Height, relatedBy: .Equal, toItem: sv, attribute: .Height, multiplier: 1.0, constant: 0.0)
    var subViewConstraints :[NSLayoutConstraint] = [cWidth, cHeight]

    //Second through Sixth SubView Add & Layout
    for i in 1..<6 {
        let tempView = UIView()
        mySubViews.append(tempView)
        sv.addSubview(tempView)
        let cWidth = NSLayoutConstraint(item: tempView, attribute: .Width, relatedBy: .Equal, toItem: mySubViews[i-1], attribute: .Width, multiplier: 1.0, constant: 0.0)
        let cHeight = NSLayoutConstraint(item: tempView, attribute: .Height, relatedBy: .Equal, toItem: mySubViews[i-1], attribute: .Height, multiplier: 1.0, constant: 0.0)
        let cLeading = NSLayoutConstraint(item: tempView, attribute: .Leading, relatedBy: .Equal, toItem: mySubViews[i-1], attribute: .Trailing, multiplier: 1.0, constant: 0.0)
        subViewConstraints += [cWidth, cHeight, cLeading]
    }

    NSLayoutConstraint.activateConstraints(subViewConstraints)
}

1 个答案:

答案 0 :(得分:1)

从我看到的操作UIScrollViews ...最好不要在viewDidLoad()中这样做。 viewDidLoad()似乎对IB中的任何x任何大小类都成立,并且不考虑创建其他大小类所需的大小调整。

每当我向UIScrollViews添加任何内容时,我都会在viewDidAppear()中完成所有操作,因为viewDidAppear()似乎会影响您的屏幕大小和约束,而viewDidLoad()实际上只是用于初始化和应该保持为真的事情在整个时间应用程序可用(大多数情况下)。