栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在UILabel上快速下划线?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在UILabel上快速下划线?

您可以使用NSAttributedString做到这一点

例:

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

编辑

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

斯威夫特4.2

class UnderlinedLabel: UILabel {override var text: String? {    didSet {        guard let text = text else { return }        let textRange = NSMakeRange(0, text.count)        let attributedText = NSMutableAttributedString(string: text)        attributedText.addAttribute(NSAttributedString.Key.underlineStyle , value: NSUnderlineStyle.single.rawValue, range: textRange)        // Add other attributes if needed        self.attributedText = attributedText        }    }}

斯威夫特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"    }

旧:

迅捷(2.0到2.3):

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        }    }}

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, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange) // Add other attributes if needed self.attributedText = attributedText        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636330.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号