Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color only underline in Swift

How do i change the color of my underline in a label? I want only the underline to change color, and not the entire text.

I have used this code to get the underline:

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

But i cant find the code, to set the underline color. Anyone who can help?

like image 798
Lasse Bickmann Avatar asked Dec 05 '22 13:12

Lasse Bickmann


1 Answers

Swift 4 Solution

You must use NSAttributedString with an array of attributes as [NSAttributedStringKey : Any].

Sample code:

import 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
    }

}
like image 103
Sébastien REMY Avatar answered Dec 30 '22 09:12

Sébastien REMY