2017-10-21 146 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 
    } 

} 
相關問題