0
我正在考慮在sizeForItemAt
這樣做,但我無法訪問我的單元格內容的高度。試過在cellForItemAt
中這樣做,因爲我們在那裏創建單元格的實例,並且可以引用它的所有內容和高度,但在此方法內設置單元格的框架大小似乎不起作用。似乎只能在sizeForItemAt
中正確設置尺寸。下面是我試圖做到這一點在cellForItemAt
一個例子(注意,在這個方法我想補充這取決於它是否有一個分配的字符串其.text
的likesCommentsLabel
觀點,這是什麼使高度動態):如何調整UICollectionView單元的大小以適應其內容?
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let feedCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FeedCell
feedCell.post = posts[indexPath.item] //This executes post setter and didSet in FeedCell class
//Determine whether to add likesCommentsLabel
if (feedCell.likesCommentsLabel.text != nil) {
feedCell.addSubview(feedCell.likesCommentsLabel)
feedCell.addConstraintsWithFormat(format: "H:|-12-[v0]|", views: feedCell.likesCommentsLabel)
feedCell.addConstraintsWithFormat(format: "V:|-8-[v0(44)]-4-[v1]-4-[v2(200)]-8-[v3(24)]-8-[v4(0.4)][v5(44)]|", views: feedCell.profileImageView, feedCell.statusTextView, feedCell.statusImageView, feedCell.likesCommentsLabel, feedCell.dividerLineView, feedCell.credibilityButton)
print("THIS RUNS")
}
else {
feedCell.addConstraintsWithFormat(format: "V:|-8-[v0(44)]-4-[v1]-4-[v2(200)]-8-[v3(0.4)][v4(44)]|", views: feedCell.profileImageView, feedCell.statusTextView, feedCell.statusImageView, feedCell.dividerLineView, feedCell.credibilityButton)
print("THIS RUNS MORE")
}
//Determine size of cell based on status text length
if let statusText = posts[indexPath.item].statusText {
let rect = NSString(string: statusText).boundingRect(with: CGSize(width: view.frame.width, height: 500), options: NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin), attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)], context: nil)
var knownHeight: CGFloat = 8.0 + 44.0 + 4.0 + 4.0 + 200.0 + 8.0 + 44.0
//Add to height of cell, if there's a likes/comments label
if (feedCell.likesCommentsLabel.text != nil) {
knownHeight = CGFloat(8.0 + 44.0 + 4.0 + 4.0 + 200.0 + 8.0 + 24.0 + 8.0 + 44.0)
}
else {
knownHeight = CGFloat(8.0 + 44.0 + 4.0 + 4.0 + 200.0 + 8.0 + 44.0)
}
//Calculate y position based off of previous cell. If no previous cell, y = 0.
if indexPath.item > 0 {
feedCell.frame = CGRect(x: 0, y: ((collectionView.cellForItem(at: collectionView.indexPathsForVisibleItems[indexPath.item - 1])?.frame.origin.y)! + (collectionView.cellForItem(at: collectionView.indexPathsForVisibleItems[indexPath.item - 1])?.frame.height)!), width: view.frame.width, height: rect.height + knownHeight + 20)
}
else {
feedCell.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: rect.height + knownHeight + 20)
}
print(feedCell.frame)
}
return feedCell
}
這實際上可以幫助你:http://corsarus.com/2015/collection-view-with-self-sizing-cells/ –