当我向我的UIScrollView添加多个子视图时,ScrollView的contentsSize
不会自动更改(如指导方针所建议的那样)。UIScrollView自动布局的内容大小问题
如果我将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)
}
我正在做基本的事情,我添加滚动视图,而不是一个视图里面的滚动视图,其中将包含所有的子视图。为该视图定义高度约束并解决问题。 我的工作是与ScrollView相等的宽度滚动视图,顶部,底部,MaginLeft和拖尾空间与定义显式高度的视图和问题已解决,我不做任何编码一切都由故事板处理 –