在NSMutableAttributedString中对UILabel的圆角

时间:2017-03-23 12:27:03

标签: ios swift3 uilabel nsmutableattributedstring

我有一个具有背景颜色和圆角的可变文本。所以我使用UILabel和NSMutableAttributedString。

    myAttributedString = NSMutableAttributedString(string:"hello")
    myAttributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.red, range: NSRange(location: 0, length: myAttributedString.length))
    myLabel.attributedText = myAttributedString
    myLabel.layer.cornerRadius = 5
    myLabel.clipsToBounds = true
    myLabel.layer.masksToBounds = true

我只在一侧获得了带圆角的标签。我该怎么办才能在四面八角?

enter image description here

1 个答案:

答案 0 :(得分:0)

只需增加UILabel(myLabel)的宽度

let myAttributedString = NSMutableAttributedString(string:"hello")
        myAttributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.red, range: NSRange(location: 0, length: myAttributedString.length))
        myLabel.attributedText = myAttributedString
        myLabel.layer.cornerRadius = 5
        myLabel.clipsToBounds = true
        myLabel.layer.masksToBounds = true

// your code is right
// just increase the width of UILabel (myLabel)