本文介绍了如何在swift中强调UILabel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 如何在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.推荐答案你可以用 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.0class 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-02 07:40