确定最后一行在 UILabel 中的结束位置
Determining the position of the end of the last line in UILabel
下面的解决方案仅适用于适合一行的名称
cell.accessoryTitleLabel.text = data.title
cell.accessoryTitleLabel.sizeToFit()
cell.discountIcon.frame.origin.x = cell.accessoryTitleLabel.frame.maxX + 7
cell.discountIcon.hidden = discount == 0
但是我需要在最后一行的末尾放一个折扣图标:
最好的方法是通过NSTextAttachment
将图像直接插入标签,然后根据要求调整图像大小,这样您就不必计算任何间距和宽度。
Swift 3 解
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
下面的解决方案仅适用于适合一行的名称
cell.accessoryTitleLabel.text = data.title
cell.accessoryTitleLabel.sizeToFit()
cell.discountIcon.frame.origin.x = cell.accessoryTitleLabel.frame.maxX + 7
cell.discountIcon.hidden = discount == 0
但是我需要在最后一行的末尾放一个折扣图标:
最好的方法是通过NSTextAttachment
将图像直接插入标签,然后根据要求调整图像大小,这样您就不必计算任何间距和宽度。
Swift 3 解
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