问题
I have a multi line UILabel which I want to set the background color exactly the same as when you highlight the text on a web browser with your mouse but cannot seem to find a solution.
This is what I got in my storyboard:
And this is what I am aiming to achieve:
This is the browser example I was mentioned above:
回答1:
Yes, use attribute text. Here for swift
let textBgColor = UIColor.greenColor()
let attributes = [
NSBackgroundColorAttributeName : textBgColor
]
let attributedString = NSAttributedString(string: Constant.kDescriptionArray[0], attributes: attributes)
descriptionLabel.attributedText = attributedString
回答2:
Try using attributed string
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]
initWithString:@"Some text line Some text line\nSome text line"];
[string addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, string.length)];
titleLabel.attributedText = string;
EDIT: Eric needed help to write swift codes. I just posted the code I had, and anyone with simple Swift knowledge should be able to write the Swift code :). Its all about learning after all :)
But any way here is the swift code.
let string = NSMutableAttributedString(string: "blah blah", attributes: [NSBackgroundColorAttributeName: UIColor.redColor()])
label.attributedText = string
来源:https://stackoverflow.com/questions/38068228/swift-ios-multi-line-uilabel-background-color-to-follow-the-text