ios – 如何在swift中强调UILabel?

ios – 如何在swift中强调UILabel?,第1张

概述如何在 Swift中强调UILabel?我搜索了Objective-C,但不能让他们在Swift工作. 您可以使用 NSAttributedString 例: let underlineAttribute = [NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]let underlineAttributedS 如何在 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?所遇到的程序开发问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1113406.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存