UILabel 自定义文本

UILabel custom Text

如何使用单个 UILabel 制作此文本或提供任何其他解决方案来实现此设计。

您可以使用 NSTextAttachment 来表示该行为。我修改 this 附件的位置。

所有代码:

  @IBOutlet weak var lbl: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
   
    let string = "Urban points users average montly saving is "

    
    let normalNameString = NSMutableAttributedString.init(string: string)

    let attachment = NSTextAttachment()
    attachment.image = imageHelper.pgImage(textValue: "QAR 115 ", lbl: lbl)
    
    attachment.bounds = CGRect(x: 0, y: (lbl.font.capHeight - attachment.image!.size.height).rounded() / 2, width: attachment.image!.size.width, height: attachment.image!.size.height)

    
    normalNameString.append(NSAttributedString(attachment: attachment))
    normalNameString.append(NSAttributedString(string: "You have saved "))
    
    let attachment2 = NSTextAttachment()
    attachment2.image = imageHelper.pgImage(textValue: "QAR 29",textColor: UIColor.yellow,backgroundColor: UIColor.black , lbl: lbl)
    attachment2.bounds = CGRect(x: 0, y: (lbl.font.capHeight - attachment2.image!.size.height).rounded() / 2, width: attachment2.image!.size.width, height: attachment2.image!.size.height)
   
    normalNameString.append(NSAttributedString(attachment: attachment2))
    normalNameString.append(NSAttributedString(string: " this month"))

    lbl.attributedText = normalNameString
}

}

class imageHelper{
static func pgImage(textValue:String,textColor : UIColor = UIColor.white , backgroundColor : UIColor = UIColor.red,lbl : UILabel) ->UIImage{
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: (textValue as NSString).size(withAttributes: [NSAttributedString.Key.font : lbl.font!]).width, height: lbl.frame.size.height))
    label.font = lbl.font
    label.textAlignment = .center
    label.textColor = textColor
    label.backgroundColor = backgroundColor
    label.layer.borderColor = UIColor.darkGray.cgColor
    label.layer.borderWidth = 1
    label.layer.cornerRadius = label.frame.size.height/2
    label.layer.masksToBounds = true
    label.text = textValue
    label.numberOfLines = 1

    UIGraphicsBeginImageContextWithOptions(label.bounds.size, false,UIScreen.main.scale)
    label.layer.render(in: UIGraphicsGetCurrentContext()!)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}
}

结果是: