'UILabel custom Text

How can I make this text using single UILabel or give any other solution to achieve this design. enter image description here



Solution 1:[1]

You can use NSTextAttachment for that behaviour. I modify this for position of attachment.

All code :

  @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!
}
}

And the result is : image here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Omer Tekbiyik