2017-10-21 148 views
0

如何更改标签中下划线的颜色?我只想要下划线来改变颜色,而不是整个文本。颜色只在Swift中加下划线

我已经使用这个代码来获取下划线:

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

但我不能找到的代码,设置下划线颜色。任何人都可以帮忙?

回答

0

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

获取参考标签

@IBOutlet weak var myLabel: UILabel! 

添加边框的标签下

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 

注意:此变通办法,你强调了整个标签。如果您需要部分undlerline文字这个解决方案并不appropiate

0

NSAttributedStringKey.underlineColor属性你想要做什么:

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

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

0

夫特4解

必须使用NSAttributedString具有属性为[NSAttributedStringKey:任何]的数组。

示例代码:

进口的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 
    } 

} 
相关问题