Шаг 1: - Создайте функцию для оценки размера вашего текста: этот метод вернет значение высоты, которое будет соответствовать вашей строке!
private func estimateFrameForText(text: String) -> CGRect {
//we make the height arbitrarily large so we don't undershoot height in calculation
let height: CGFloat = 999
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)
}
Step 2: Используйте или переопределите метод делегата ниже:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var height: CGFloat = 0
//we are just measuring height so we add padding constant to give the label some room to breathe!
var padding: CGFloat = 10
let stringFromViewModel = “Hello please pass your string here from array…”
//estimate each cell's height
height = estimateFrameForText(stringFromViewModel).height + padding
return CGSize(width: yourDesiredWidth, height: height)
}