如何在swift中强调UILabel? [英] How to underline a UILabel in swift?

查看:79
本文介绍了如何在swift中强调UILabel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift中强调 UILabel ?我搜索了Objective-C但却无法让它们在Swift中工作。

How to underline a UILabel in Swift? I searched the Objective-C ones but couldn't quite get them to work in Swift.

推荐答案

你可以用< a href =https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/NSAttributedString_UIKit_Additions/index.html#//apple_ref/c/tdef/NSUnderlineStyle> NSAttributedString

示例:

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

编辑

要为一个UILabel的所有文本提供相同的属性,我建议你继承UILabel和覆盖文本,例如:

To have the same attributes for all texts of one UILabel, I suggest you to subclass UILabel and overriding text, like that:

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

OLD:

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

这篇关于如何在swift中强调UILabel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆