當我向我的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和拖尾空間與定義顯式高度的視圖和問題已解決,我不做任何編碼一切都由故事板處理 –