Skip to content

Instantly share code, notes, and snippets.

class ArticleClass {
let title: String
let url: URL
var readCount: Int = 0
init(title: String, url: URL) {
self.title = title
self.url = url
}
}
let text = dataSource.item(at: indexPath.item)
guard let nib = Bundle.main.loadNibNamed("CustomCell", owner: CustomCell.self, options: nil), let cell = nib?[0] as? CustomCell else {
return
}
// Ensure that your content has been set
cell.label.text = text
// Assuming your custom cell has a content view
cell.contentView.setNeedsLayout()
cell.contentView.layoutIfNeeded()
func collectionView(_ collectionView: UICollectionView, layout: FlexibleRowHeightGridLayout, heightForItemAt indexPath: IndexPath) -> CGFloat {
let text = dataSource.item(at: indexPath.item)
let font = Typography(for: .cellText).font()
return layout.textHeight(text, font: font)
}
func collectionView(_ collectionView: UICollectionView, layout: FlexibleRowHeightGridLayout, heightForItemAt indexPath: IndexPath) -> CGFloat {
let text = dataSource.item(at: indexPath.item)
let font = UIFont.preferredFont(forTextStyle: .body)
return layout.textHeight(text, font: font)
}
let layout = FlexibleRowHeightGridLayout()
layout.delegate = self
collectionView.collectionViewLayout = layout
let layout = FlexibleRowHeightGridLayout()
layout.delegate = self
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
var newFrame = layoutAttributes.frame
// Make any additional adjustments to the cell's frame
newFrame.size = size
layoutAttributes.frame = newFrame
return layoutAttributes
}
override func awakeFromNib() {
super.awakeFromNib()
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentView.leftAnchor.constraint(equalTo: leftAnchor),
contentView.rightAnchor.constraint(equalTo: rightAnchor),
contentView.topAnchor.constraint(equalTo: topAnchor),
contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
@IBOutlet weak var layout: UICollectionViewFlowLayout! {
didSet {
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}