Search code examples
iosswiftuilabelnsattributedstring

Image attachment as first item (left aligned) in NSAttributed string


I am trying to add an image to a UILabel using a NSAttributedString with a NSTextAttachment

func attributedString(string:String)->NSAttributedString {
    let label:NSMutableAttributedString = NSMutableAttributedString()

    let string = NSAttributedString(string: string)
    let attachment = NSTextAttachment()
    attachment.image = #imageLiteral(resourceName: "WaterIcon")
    let imageString = NSAttributedString(attachment: attachment)

    label.append(string)
    label.append(imageString)

    return label
}

enter image description here

when I switch

    label.append(imageString)
    label.append(string)

… which is what I want regarding the order, the image doesn't show up at all :-(

How can I add the image as first item in the string?

enter image description here


Solution

  • You code works just fine for me with the two append statements swapped:

    enter image description here

    Perhaps there is a problem with how your label is sized/positioned, or how you are assigning the attributed string to the label. But you have not shown any of that part of your code, so who knows what you're doing wrong?