2017-10-21 79 views
0

Comment changer la couleur de mon soulignement dans une étiquette? Je veux que le soulignement change de couleur, et non le texte entier.Couleur uniquement soulignée dans Swift

J'ai utilisé ce code pour obtenir le underline:

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

Mais je ne peux pas trouver le code, pour définir la couleur de soulignement. Quelqu'un qui peut aider?

Répondre

0

Une autre solution pourrait être d'ajouter une bordure de ligne unique sous l'étiquette, qui agit comme un soulignement.

référence à la Get étiquette

@IBOutlet weak var myLabel: UILabel! 

Ajouter la frontière sous le label

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 

Remarque: cette solution de contournement vous soulignez l'étiquette entière. Si vous devez partiellement undlerline le texte cette solution n'appropiate

0

L'attribut NSAttributedStringKey.underlineColor fait ce que vous voulez:

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

Cela définira la couleur de soulignement à l'orange alors que la couleur du texte restera noir.

0

Swift 4 Solution

Vous devez utiliser NSAttributedString avec un éventail d'attributs comme [NSAttributedStringKey: Tout].

Exemple de code:

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

}