The solution below works correctly only for names that fit on one line
cell.accessoryTitleLabel.text = data.title
cell.accessoryTitleLabel.sizeToFit()
cell.discountIcon.frame.origin.x = cell.accessoryTitleLabel.frame.maxX + 7
cell.discountIcon.hidden = discount == 0
But I need to put a discount icon at the end of the last line:
For example, to make UILabel support two lines, we will set the numberOfLines property to 2. Although, in some situations, setting the numberOfLines property alone is not enough. For example, if the height of UILabel is set, then it will have a higher priority and the number of lines property will not be respected.
A view that displays one or more lines of informational text.
The best way is to insert your image directly on label by NSTextAttachment
and resizing the image as per requirement, in that way you don't have to calculate any spacing and width.
Swift 3 solution
var img_attachment = NSTextAttachment()
img_attachment.image = UIImage(named: "name_of_image")
img_attachment.bounds = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(ImgWidth), height:CGFloat(ImgHeight)) // you can specify the size and bounds of discount image
var attributedString = NSAttributedString(attachment: img_attachment)
var lblString = NSMutableAttributedString(string: "your text here")
lblString.append(attributedString)
cell.accessoryTitleLabel.attributedText = lblString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With