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

时间:2017-04-07 08:54:23

标签: ios swift user-interface labels

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

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

但我需要在最后一行末尾加上折扣图标: enter image description here

1 个答案:

答案 0 :(得分:2)

最好的方法是将图片直接插入标签 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