您可以使用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 } }}


