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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With