Создайте имя метода estimateFrameForText
, и этот метод вернет значение высоты, которое будет соответствовать вашей строке!
private func estimateFrameForText(text: String) -> CGRect {
//we make the height arbitrarily large so we don't undershoot height in calculation
let height: CGFloat = 320
let size = CGSize(width: yourDesiredWidth, height: height)
let options = NSStringDrawingOptions.UsesFontLeading.union(.UsesLineFragmentOrigin)
let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(18, weight: UIFontWeightLight)]
return NSString(string: text).boundingRectWithSize(size, options: options, attributes: attributes, context: nil)
}
Вы должны использовать UICollectionViewDelegateFlowLayout
и реализовать sizeForItemAt
, как показано ниже. [убедитесь, что ваш класс продлен UICollectionViewDelegateFlowLayout
]
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset
var referenceWidth: CGFloat = collectionView.safeAreaLayoutGuide.layoutFrame.width
var referenceHeight: CGFloat = 320
//we are just measuring height so we add padding constant to give the label some room to breathe!
var padding: CGFloat = <someArbitraryPaddingValue>
//estimate each cell's height
if let text = array?[indexPath.item].text {
referenceHeight= estimateFrameForText(text).height + padding
}
return CGSize(width: referenceWidth, height: referenceHeight)
}