【发布时间】:2017-08-08 19:56:27
【问题描述】:
我正在尝试构建一个UICollectionView,它具有自我调整大小的UICollectionViewCells。我使用的是UICollectionView 而不是UITableView,因为我想在 iPhone 上使用列表视图,在 iPad 上使用网格视图。
我已经设置了一个示例项目here。
这是最简单的代码。从 Storyboard 加载的 UICollectionView。有一个UICollectionViewCell 和一个UILabel。 UILabel 具有将其固定到单元格边缘的约束。
UICollectionView 有一个UICollectionViewFlowLayout。如果我将itemSize 设置为UICollectionViewFlowLayoutAutomaticSize,则会出现约束错误。
ViewController 中的代码非常简单:
class ViewController: UIViewController, UICollectionViewDataSource {
// MARK: - Outlets
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var collectionViewFlowLayout: UICollectionViewFlowLayout!
// MARK: - view lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 10.0, *) {
// This causes constaint errors.
// collectionViewFlowLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize
// collectionViewFlowLayout.estimatedItemSize = CGSize(width: 300, height: 50)
} else {
// Fallback on earlier versions
}
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath)
guard let itemCell = cell as? ItemCell else {
return cell
}
itemCell.label.text = "blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah"
return cell
}
}
【问题讨论】:
-
你能发布你得到的错误吗?您是否尝试在单元格/标签上将
translatesAutoresizingMasksIntoConstraints设置为false? -
translatesAutoresizingMasksIntoConstraints在情节提要中设置为 false。我没有看到任何约束错误。 -
当我添加
collectionViewFlowLayout.itemSize = UICollectionViewFlowLayoutAutomaticSize然后我得到:The behavior of the UICollectionViewFlowLayout is not defined because: the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
标签: ios uicollectionview autolayout