I am trying to calculate the height of a label so I can set the height of its cell dynamically. This works fine, like this:
let commentText = itemsFeed[indexPath.item].comment
let commentRect = NSString(string: commentText!).boundingRect(with:CGSize(width: rectWidth, height: 1000), options: NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin), attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 16)], context: nil)
let commentHeight = ceil(commentRect.height)
This returns all the right values and I can dynamically set the height based on commentHeight.
However, when I don't add a comment, I would like to return 0 for commentHeight, but instead Swift returns 20 (the default height of a one line label). How can I override this?
I have tried to add an if statement like this:
if(commentText?.isEmpty)! {
let commentHeight = 0
} else {
let commentText = itemsFeed[indexPath.item].comment
let commentRect = NSString(string: commentText!).boundingRect(with:CGSize(width: rectWidth, height: 1000), options: NSStringDrawingOptions.usesFontLeading.union(NSStringDrawingOptions.usesLineFragmentOrigin), attributes: [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 16)], context: nil)
let commentHeight = ceil(commentRect.height)
}
But this returns Use of unresolved identifier 'commentHeight' in the return of my CGSize (where commentHeight is called for).
Any tips or tricks on how to achieve this, so that commentHeight would be 0 if there is no text?
(All code presented is inside the sizeForItemAt method)
Aucun commentaire:
Enregistrer un commentaire