在Swift中只有下划线的颜色

Las*_*ann 1 label underline nsattributedstring swift

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

我已使用此代码来强调以下内容:

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

但是我找不到代码来设置下划线颜色。谁能帮忙?

Séb*_*EMY 6

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
    }

}
Run Code Online (Sandbox Code Playgroud)


Luc*_*adi 2

另一种解决方案可能是在标签下添加一条线边框,充当下划线。

获取标签参考

@IBOutlet weak var myLabel: UILabel!
Run Code Online (Sandbox Code Playgroud)

在标签下添加边框

    let labelSize = myLabel.frame.size
    let border = CALayer()
    let w = CGFloat(2.0)

    border.borderColor = UIColor.yellow.cgColor  // <--- Here the underline color
    border.frame = CGRect(x: 0, y: labelSize.height - w, width:  labelSize.width, height: labelSize.height)
    border.borderWidth = w
    myLabel.layer.addSublayer(border)
    myLabel.layer.masksToBounds = true
Run Code Online (Sandbox Code Playgroud)

注意:通过此解决方法,您可以在整个标签下划线。如果您需要对文本进行部分下划线,则此解决方案不合适