2016-06-07 101 views
1

當水平尺寸類更改時,我在調整單元格佈局時遇到問題。當traitCollection發生變化時更改單元格佈局

我的單元有一個stackView,我希望該軸對於緊湊尺寸類是水平的,對於常規是垂直的。

這是我的嘗試:

override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) { 
    if previousTraitCollection?.horizontalSizeClass != traitCollection.horizontalSizeClass { 
     self.collectionView?.reloadData() 
    } 
} 

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell 

    switch traitCollection.horizontalSizeClass { 
    case .Compact: 
     cell.stackView.axis = .Horizontal 
    default: 
     cell.stackView.axis = .Vertical 
    } 

    return cell 
} 

但結果是,並非所有的細胞更新它們的佈局,SE以下的gif。

編輯: 我已經證實,軸是由cellForItem和在細胞類本身正確打印改變。所以,這個問題似乎是細胞沒有重繪..

Cell layout problems

任何建議,應該怎樣解決這個問題?

Github Repo

+0

實現'traitCollectionDidChange'你重裝。通過做'willChange'你的細胞仍然看到舊的特徵集合http://stackoverflow.com/questions/24716136/where-to-update-autolayout-constraints-when-size-changes – Paulw11

+0

謝謝,但它仍然無法正常工作。當我註銷'cellForItem'中的'traitCollection'時,它會在使用willChange時更新,但我會用您的建議更新我的問題。 – LarsJK

回答

2

調用layoutIfNeeded()添加到cellForItemAtIndexPath方法,以獲取堆棧以重新佈局其內容:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell 

    switch traitCollection.horizontalSizeClass { 
    case .Compact: 
     cell.stackView.axis = .Horizontal 
    default: 
     cell.stackView.axis = .Vertical 
    } 

    cell.stackView.layoutIfNeeded() 

    return cell 
} 
+0

非常感謝!這工作。 – LarsJK

相關問題