确定 UILabel 中最后一行末尾的位置

Ser*_*gey 5 user-interface label ios swift

下面的解决方案仅适用于适合一行的名称

        cell.accessoryTitleLabel.text = data.title
        cell.accessoryTitleLabel.sizeToFit()
        cell.discountIcon.frame.origin.x = cell.accessoryTitleLabel.frame.maxX + 7
        cell.discountIcon.hidden = discount == 0
Run Code Online (Sandbox Code Playgroud)

但我需要在最后一行的末尾放置一个折扣图标: 在此输入图像描述

Viz*_*llx 5

最好的方法是直接在标签上插入图像根据要求调整图像大小NSTextAttachment,这样您就不必计算任何间距和宽度。


斯威夫特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
Run Code Online (Sandbox Code Playgroud)