颜色只在Swift下划线

时间:2017-10-21 08:27:13

标签: swift label nsattributedstring underline

如何更改标签中下划线的颜色?我只希望下划线改变颜色,而不是整个文本。

我已使用此代码获取下划线:

let underlineAttribute = [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue]
let underlineAttributedString = NSAttributedString(string: "\(nearSavings[indexPath.row]) ,-", attributes: underlineAttribute)
cell.detailTextLabel?.attributedText = underlineAttributedString

但我找不到代码,设置下划线颜色。有谁可以提供帮助?

4 个答案:

答案 0 :(得分:3)

Swift 4解决方案

您必须将NSAttributedString与属性数组一起使用为[NSAttributedStringKey:Any]。

示例代码:

导入UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Colored Underline Label
        let labelString = "Underline Label"
        let textColor: UIColor = .blue
        let underLineColor: UIColor = .red
        let underLineStyle = NSUnderlineStyle.styleSingle.rawValue

        let labelAtributes:[NSAttributedStringKey : Any]  = [
            NSAttributedStringKey.foregroundColor: textColor,
            NSAttributedStringKey.underlineStyle: underLineStyle,
            NSAttributedStringKey.underlineColor: underLineColor
        ]

        let underlineAttributedString = NSAttributedString(string: labelString,
                                                           attributes: labelAtributes)

        myLabel.attributedText = underlineAttributedString
    }

}

答案 1 :(得分:1)

另一种解决方案可能是在标签下添加一个单行边框,作为下划线。

参考标签

UserDetails

在标签下添加边框

UserRepository
  

注意:使用此解决方法,您可以为整个标签加下划线。如果你需要部分地删除文本,这个解决方案是不合适的

答案 2 :(得分:1)

NSAttributedStringKey.underlineColor属性可以满足您的需求:

let underlineAttributes = [
   NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue,
   NSAttributedStringKey.underlineColor: UIColor.orange
] as [NSAttributedStringKey : Any]
let underlineAttributedString = NSAttributedString(string: "Test", attributes: underlineAttributes)

这会将下划线颜色设置为橙色,而文本颜色将保持黑色。

答案 3 :(得分:1)

Swift 5解决方案

class UnderlinedLabel: UILabel {

override var text: String? {
didSet {
    guard let text = text else { return }
    let textColor: UIColor = .black
    let underLineColor: UIColor = .lightGray
    let underLineStyle = NSUnderlineStyle.single.rawValue
    let labelAtributes:[NSAttributedString.Key : Any]  = [
        NSAttributedString.Key.foregroundColor: textColor,
        NSAttributedString.Key.underlineStyle: underLineStyle,
        NSAttributedString.Key.underlineColor: underLineColor
    ]
    self.attributedText = NSAttributedString(string: text, attributes: labelAtributes)
    }
}

}

用法: 只需在情节提要中为您的标签提供UnderlinedLabel类