UITextView text background colour

2019-07-24 05:27发布

问题:

I am trying to get a transparent UITextView, and I know how to set it. What I also want is like a coloured background right under the text that has been shown. Again the text view background will set the entire view rectangle to a given colour, what I want is colour just under the text. Any easy way of achieving such thing?

回答1:

From what I can tell you're trying to accomplish a highlighting effect on the text. If this is the case you could use NSAttributedString. It allows you to set the background color of the text and not the view background.

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"Test String"];
[attributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, 11)];

Then set the attributedText property on your UITextView:

textView.attributedText = attributedString;