当我将多个子视图添加到我的UIScrollView时,ScrollView的contentsSize
不会自动更改(如准则建议的那样)。
如果将contentsSize
设置为宽度的6倍(我正在制作6页滚动视图),则视图的布局将正确。但是我没有手动设置contentsSize
,scrollView不会滚动,并且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)
}
最佳答案
从我看到的处理UIScrollViews的结果来看,最好不要在viewDidLoad()中这样做。 viewDidLoad()似乎适用于IB中的any x any size类,并且不考虑创建其他大小类所需的调整大小。
每当我将任何内容添加到UIScrollViews时,我都将在viewDidAppear()中完成所有操作,因为似乎viewDidAppear()会考虑您的屏幕尺寸和约束,而viewDidLoad()实际上仅用于初始化,并且整个过程应该保持正确应用可用的时间(大部分时间)。