微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 如何在swift中强调UILabel?

如何在 Swift中强调UILabel?我搜索了Objective-C,但不能让他们在Swift工作.

解决方法

您可以使用 NSAttributedString

例:

let underlineAttribute = [NSUnderlinestyleAttributeName: NSUnderlinestyle.StyleSingle.rawValue]
let underlineAttributedString = NSAttributedString(string: "StringWithUnderLine",attributes: underlineAttribute)
myLabel.attributedText = underlineAttributedString

编辑

为了对一个UILabel的所有文本具有相同的属性,我建议您将UILabel子类化并覆盖文本,如下所示:

Swift 3.0

class UnderlinedLabel: UILabel {

    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSMakeRange(0,text.characters.count)
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlinestyleAttributeName,value: NSUnderlinestyle.styleSingle.rawValue,range: textRange)
            // Add other attributes if needed
            self.attributedText = attributedText
        }
    }
}

你把你的文本这样:

@IBOutlet weak var label: UnderlinedLabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "StringWithUnderLine"
    }

旧:

Swift(2.0至2.3):

class UnderlinedLabel: UILabel {

    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSMakeRange(0,value:NSUnderlinestyle.StyleSingle.rawValue,range: textRange)
            // Add other attributes if needed

            self.attributedText = attributedText
        }
    }
}

Swift 1.2:

class UnderlinedLabel: UILabel {

    override var text: String! {
        didSet {
            let textRange = NSMakeRange(0,count(text))
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlinestyleAttributeName,range: textRange)
            // Add other attributes if needed

            self.attributedText = attributedText
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐