0
私はsizeForItemAt
でこれを行うことを考えていましたが、そこに自分のセルのコンテンツの高さにアクセスすることはできません。 cellForItemAt
でそれをやろうとしました。そこにあるセルのインスタンスを作成していて、その内容とその高さをすべて参照できますが、このメソッド内のセルのフレームサイズを設定しても機能しません。サイズはsizeForItemAt
でしか正しく設定できないようです。ここでは(この方法で私はそれがその.text
に割り当てられた文字列を持っており、これは高さが動的にするものであるかどうかに応じてlikesCommentsLabel
ビューを追加することに注意してください)cellForItemAt
でそれをやろうとしている私の例です:内容に合わせて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/ –