Search code examples
iosswiftnsattributedstringnsmutableattributedstring

Remove the colored background of empty spaces of a UILabel that uses NSMutableAttributedString


I would like to know if is it possible, on a UILabel that uses NSMutableAttributedString, to remove the colored background that is set in the empty spaces on the "beginning" of each line, when the align is set to right.

Obs.: everything works fine when the align is set to left

enter image description here

enter image description here

This is what I expect:

enter image description here


Extra question: Is it possible to leave a space between the lines without a color?


Solution

  • Set backgroundColor of your label to White or Clear color and apply the background color to your NSMutableAttributedString as like below,

    //In Swift
    let mutableAttributedString = NSMutableAttributedString() //Initialize your string here
    mutableAttributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.yellow, range: NSMakeRange(0, mutableAttributedString.length))
    
    //In Objective C
    NSMutableAttributedString *mutableAttributedString; //Initialize your string here
    [mutableAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(0, mutableAttributedString.length)];
    

    If you are using storyBoard change backgroundColor of attributed string as show in attached image. enter image description here

    Just realized that above solution will work for below scenarios,

    1. Maximum two lines with Left alignment
    2. Maximum one line with Right and Center alignments

    Please follow this post for complete solution.