Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining the position of the end of the last line in UILabel [duplicate]

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: enter image description here

like image 273
Sergey Avatar asked Apr 07 '17 08:04

Sergey


People also ask

How do you make UILabel two lines?

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.

What is UILabel in Swift?

A view that displays one or more lines of informational text.


1 Answers

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

like image 76
Vizllx Avatar answered Sep 30 '22 15:09

Vizllx