2016-11-21 34 views
0

對面的其他人都好像是問。我有一個集合視圖,其中我添加了一個加載的.xib作爲子視圖。很簡單。我如何限制的UIView到UICollectionViewCell

但是,collectionView單元格的大小會根據不同的標準在運行時更改,因此我需要將子視圖正確地限制爲collectionViewCell的contentView的大小。在試圖做到這一點,我有這樣的代碼時,我添加子視圖:

/** 
Used to present a view in the collectionView. WidetView is a subclass of UIView 
*/ 
class WidgetCell: UICollectionViewCell, Reusable { 
    var widgetView: WidgetView! { 
     didSet { 
      for view in contentView.subviews { 
       view.removeFromSuperview() 
      } 

      contentView.addSubview(widgetView) 
      let views = ["view": widgetView as Any] 
      var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: views) 
      constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: views)) 

      contentView.addConstraints(constraints) 
     } 
    } 
} 

不幸的是,這是怎麼介紹的是沒有一套正確的約束意見。添加的UIView與.xib中定義的大小相同。

unsized cells

我該如何解決這個問題?如果你想要一個樣本項目(SWIFT 3)看這裏:https://github.com/AaronBratcher/FitToCell

+0

找到了我的問題。我想設置添加的UIView的框架以匹配contentView.frame,而不是使用約束。 –

+0

很高興你找到了解決辦法,然而警告說,做這種方式將意味着框架不會更新,如果你把你的設備的風景,你必須做手工。 –

+0

結果contentView並不總是適當的大小。我需要將單元格大小傳遞給WidgetCell類,並將widgetView.frame.size設置爲 –

回答

0

由於單元格的預期大小已知用於佈局,因此將該大小傳遞給WidgetCell實例,然後設置視圖的幀大小。

final class WidgetCell: UICollectionViewCell { 
    var cellSize: CGSize? 
    var widgetView: WidgetView! { 
     didSet { 
      for view in contentView.subviews { 
       view.removeFromSuperview() 
      } 

      let frame: CGRect 
      if let cellSize = cellSize { 
       frame = CGRect(origin: CGPoint(x: 0, y: 0), size: cellSize) 
      } else { 
       frame = contentView.frame 
      } 

      widgetView.frame = frame 
      widgetView.setNeedsLayout() 
      contentView.addSubview(widgetView) 
     } 
    } 
} 
0

它調用contentView.activateConstraints(constraints)與您現有的代碼,然後在其中細胞顯示,cell.layoutIfNeeded()點的簡單情況。這迫使單元重新計算其子視圖的邊界。

+0

一個好主意,我研究它。新添加的約束在默認情況下處於活動狀態,並且可以通過NSLayoutConstraint類來激活/取消激活。無論如何,當我創建collectionViewCell並且沒有幫助時,我嘗試了激活約束和設置layoutIfNeeded的建議。如果您還有其他問題,請嘗試關於該項目的想法。 –