對面的其他人都好像是問。我有一個集合視圖,其中我添加了一個加載的.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中定義的大小相同。
我該如何解決這個問題?如果你想要一個樣本項目(SWIFT 3)看這裏:https://github.com/AaronBratcher/FitToCell
找到了我的問題。我想設置添加的UIView的框架以匹配contentView.frame,而不是使用約束。 –
很高興你找到了解決辦法,然而警告說,做這種方式將意味着框架不會更新,如果你把你的設備的風景,你必須做手工。 –
結果contentView並不總是適當的大小。我需要將單元格大小傳遞給WidgetCell類,並將widgetView.frame.size設置爲 –