HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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
        }
    }
}

大佬总结

以上是大佬教程为你收集整理的ios – 如何在swift中强调UILabel?全部内容,希望文章能够帮你解决ios – 如何在swift中强调UILabel?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。