19

I just wanted to know how could i change the background color of an NSAttributedString, i can see the background being white all the time, but i want to make it black.

Is that possible?? Many thanks!

4 Answers 4

33

I think you want NSBackgroundColorAttributeName. Such as:

[mutableAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:selectedRange];
Sign up to request clarification or add additional context in comments.

2 Comments

Works for me. iOS is the only thing I've used it with.
What if I want to put a background color only the text, words and spaces, without putting bg color on the new line? Thanks
3

For Swift:

attributedString.addAttribute(NSBackgroundColorAttributeName, value: yourColor, range: NSMakeRange(0, tillLocation))

Helpful link - Different way to attribute a string

Comments

0

The best plan would really be to draw the string on a view with a black background.

1 Comment

I found out that i wanted to change the color for the NSAttributedStringView and not the string :) silly me... Thanks!
0

For Swift 5:

someMutableAttributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: <#your color#>, range: <#your range#>)

1 Comment

NSAttributedString.Key is redundant. Just .backgroundColor would suffice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.