Home > Enterprise >  Align the image and text in NSAttributed text
Align the image and text in NSAttributed text

Time:02-25

I need to align the image and text horizontally and assign that string to a UILabel. Below is my code:

let attachment = NSTextAttachment()
let text = "Current user."
attachment.image = UIImage(named: "icon-horizontal-line")                        
let attachmentString = NSAttributedString(attachment: attachment)
let mutableAttributedString = NSMutableAttributedString()
mutableAttributedString.append(attachmentString)                        
let string = NSMutableAttributedString(string: text, attributes: [:])
mutableAttributedString.append(string)
label.attributedText = mutableAttributedString

And my result looks like this :

app_screenshot

I want both the image and string to be aligned something similar to : ----- Current User.

CodePudding user response:

You need to set the bounds of the attachment. Here is your updated code.

        let attachment = NSTextAttachment()
        let text = "Current user."
        let img = UIImage(named: "icon-horizontal-line")
        let font = UIFont.systemFont(ofSize: 18)
        attachment.image = img
        let mid = font.descender   font.capHeight
        attachment.bounds = CGRect(x: 0, y: font.descender - img!.size.height / 2   mid   2, width: img!.size.width, height: img!.size.height)
        let attachmentString = NSAttributedString(attachment: attachment)
        let mutableAttributedString = NSMutableAttributedString()
        mutableAttributedString.append(attachmentString)
        let string = NSMutableAttributedString(string: text, attributes: [:])
        mutableAttributedString.append(string)

        label.attributedText = mutableAttributedString
  • Related