Swift iOS. Multi line UILabel background color to follow the text

旧街凉风 提交于 2019-12-24 00:59:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!