Come sottolineare un'etichetta UIL in modo rapido?


96

Come sottolineare una UILabelin Swift? Ho cercato quelli Objective-C ma non sono riuscito a farli funzionare in Swift.


7
NSAttributedString?
Larme

che cosa è con le antipatie? c'è un'ovvia confusione qui con gli attributi che sembrano chiamate di metodo in objc
Esqarrouth

qui puoi ottenere il modo più semplice stackoverflow.com/questions/28268060/…
Kapil B

ecco il modo più semplice [ stackoverflow.com/questions/28268060/…
Kapil B

Risposte:


222

Puoi farlo usando NSAttributedString

Esempio:

let underlineAttribute = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue]
let underlineAttributedString = NSAttributedString(string: "StringWithUnderLine", attributes: underlineAttribute)
myLabel.attributedText = underlineAttributedString

MODIFICARE

Per avere gli stessi attributi per tutti i testi di una UILabel, ti suggerisco di sottoclassare UILabel e sovrascrivere il testo, in questo modo:

Swift 4.2

class UnderlinedLabel: UILabel {

override var text: String? {
    didSet {
        guard let text = text else { return }
        let textRange = NSMakeRange(0, text.count)
        let attributedText = NSMutableAttributedString(string: text)
        attributedText.addAttribute(NSAttributedString.Key.underlineStyle , value: NSUnderlineStyle.single.rawValue, range: textRange)
        // Add other attributes if needed
        self.attributedText = attributedText
        }
    }
}

Swift 3.0

class UnderlinedLabel: UILabel {
    
    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSMakeRange(0, text.characters.count)
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
            // Add other attributes if needed
            self.attributedText = attributedText
        }
    }
}

E metti il ​​tuo testo in questo modo:

@IBOutlet weak var label: UnderlinedLabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        label.text = "StringWithUnderLine"
    }

VECCHIO:

Swift (da 2.0 a 2.3):

class UnderlinedLabel: UILabel {
    
    override var text: String? {
        didSet {
            guard let text = text else { return }
            let textRange = NSMakeRange(0, text.characters.count)
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
            // Add other attributes if needed
            
            self.attributedText = attributedText
        }
    }
}

Swift 1.2:

class UnderlinedLabel: UILabel {
    
    override var text: String! {
        didSet {
            let textRange = NSMakeRange(0, count(text))
            let attributedText = NSMutableAttributedString(string: text)
            attributedText.addAttribute(NSUnderlineStyleAttributeName, value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
            // Add other attributes if needed
            
            self.attributedText = attributedText
        }
    }
}

Quale sarebbe il modo migliore per de-sottolineare?
N. Der

Mi chiedevo da molto tempo: perché dobbiamo usare rawValue altrimenti va in crash?
Bruno Muniz

Dovresti passare il UTF16conteggio invece del conteggio dei caratteri quando crei il tuo text RangeNSRange
Leo Dabus

113

Swift 5 e 4.2 un rivestimento:

label.attributedText = NSAttributedString(string: "Text", attributes:
    [.underlineStyle: NSUnderlineStyle.single.rawValue])

Swift 4 one liner:

label.attributedText = NSAttributedString(string: "Text", attributes:
    [.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])

Swift 3 un rivestimento:

label.attributedText = NSAttributedString(string: "Text", attributes:
      [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])

1
NSUnderlineStyle.styleSingle.rawValue è stato rinominato NSUnderlineStyle.single.rawValue in swift 4.2
Skaal

Come faccio a de-sottolineare?
N. Der

@ N.Der Imposta di nuovo un testo normale da etichettare
diJeevan

15

Se stai cercando un modo per farlo senza eredità:

Swift 5

extension UILabel {
    func underline() {
        if let textString = self.text {
          let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
                                          value: NSUnderlineStyle.single.rawValue,
                                          range: NSRange(location: 0, length: attributedString.length))
          attributedText = attributedString
        }
    }
}

Swift 3/4

// in swift 4 - switch NSUnderlineStyleAttributeName with NSAttributedStringKey.underlineStyle
extension UILabel {
    func underline() {
        if let textString = self.text {
          let attributedString = NSMutableAttributedString(string: textString)
          attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: attributedString.length))
          attributedText = attributedString
        }
    }
}


extension UIButton {
  func underline() {
    let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
    attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.styleSingle.rawValue, range: NSRange(location: 0, length: (self.titleLabel?.text!.characters.count)!))
    self.setAttributedTitle(attributedString, for: .normal)
  }
}

Dovresti passare il UTF16conteggio invece del conteggio dei personaggi quando crei il tuoNSRange
Leo Dabus

8

Solo una piccola correzione per la risposta di Shlome in Swift 4 e Xcode 9 .

extension UILabel {
    func underline() {
        if let textString = self.text {
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedStringKey.underlineStyle,
                                          value: NSUnderlineStyle.styleSingle.rawValue,
                                          range: NSRange(location: 0, length: attributedString.length - 1))
            attributedText = attributedString
        }
    }
}

    extension UIButton {
        func underline() {
            let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
            attributedString.addAttribute(NSAttributedStringKey.underlineStyle,
                                          value: NSUnderlineStyle.styleSingle.rawValue,
                                          range: NSRange(location: 0, length: (self.titleLabel?.text!.count)!))
            self.setAttributedTitle(attributedString, for: .normal)
        }
    }

Dovresti passare il UTF16conteggio invece del conteggio dei personaggi quando crei il tuoNSRange
Leo Dabus

8

Swift 4:

1- Crea un'estensione String per ottenere attributeText.

2- Utilizzare esso

Estensione:

import UIKit
extension String {
   func getUnderLineAttributedText() -> NSAttributedString {
       return NSMutableAttributedString(string: self, attributes: [.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])
   }
}

Come usarlo su buttton:

if let title = button.titleLabel?.text{
    button.setAttributedTitle(title.getUnderLineAttributedText(), for: .normal)
}

Come usarlo sulle etichette:

if let title = label.text{    
   label.attributedText = title.getUnderLineAttributedText()
}

Oppure la versione Stoyboard



4

Stessa risposta in Swift 4.2

Per UILable

extension UILabel {
    func underline() {
        if let textString = self.text {
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
                                          value: NSUnderlineStyle.single.rawValue,
                                          range: NSRange(location: 0, length: textString.count))
            self.attributedText = attributedString
        }
    }
}

Chiama UILabel come di seguito

myLable.underline()

Per UIButton

extension UIButton {
    func underline() {
        if let textString = self.titleLabel?.text {

            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
                                          value: NSUnderlineStyle.single.rawValue,
                                          range: NSRange(location: 0, length: textString.count))
            self.setAttributedTitle(attributedString, for: .normal)
        }

    }
}

Chiama il pulsante UIB come sotto

myButton.underline()

Ho esaminato le risposte precedenti e alcune di esse sono il valore del testo che viene scartato con la forza . Suggerirò di ottenere valore scartando in sicurezza. Ciò eviterà il crash in caso di valore nullo. Spero che questo ti aiuti :)


semplicemente bello e facile
Jan Bergström

Dovresti passare il UTF16conteggio invece del conteggio dei personaggi quando crei il tuoNSRange
Leo Dabus

Se hai già l'estensione per UILabel, IMO è più semplice chiamare myButton.titleLabel? .Underline (), o almeno usarlo all'interno della funzione underline () nell'estensione per UIButton.
boherna

4

Swift 4, 4.2 e 5.

  @IBOutlet weak var lblUnderLine: UILabel!

Ho bisogno di sottolineare un testo particolare in UILabel. Quindi, trova l'intervallo e imposta gli attributi.

    let strSignup = "Don't have account? SIGNUP NOW."
    let rangeSignUp = NSString(string: strSignup).range(of: "SIGNUP NOW.", options: String.CompareOptions.caseInsensitive)
    let rangeFull = NSString(string: strSignup).range(of: strSignup, options: String.CompareOptions.caseInsensitive)
    let attrStr = NSMutableAttributedString.init(string:strSignup)
    attrStr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.white,
                           NSAttributedString.Key.font : UIFont.init(name: "Helvetica", size: 17)! as Any],range: rangeFull)
    attrStr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.white,
                           NSAttributedString.Key.font : UIFont.init(name: "Helvetica", size: 20)!,
                          NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue as Any],range: rangeSignUp) // for swift 4 -> Change thick to styleThick
    lblUnderLine.attributedText = attrStr

Produzione

inserisci qui la descrizione dell'immagine


3

Sottolineato a più stringhe in una frase.

extension UILabel {
    func underlineMyText(range1:String, range2:String) {
        if let textString = self.text {

            let str = NSString(string: textString)
            let firstRange = str.range(of: range1)
            let secRange = str.range(of: range2)
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: firstRange)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: secRange)
            attributedText = attributedString
        }
    }
}

Usa in questo modo.

    lbl.text = "By continuing you agree to our Terms of Service and Privacy Policy."
    lbl.underlineMyText(range1: "Terms of Service", range2: "Privacy Policy.")

1
Come seguirai il tocco?
karthikeyan

2

Swift 4 modifiche. Ricorda di utilizzare NSUnderlineStyle.styleSingle.rawValue invece di NSUnderlineStyle.styleSingle .

   'let attributedString = NSAttributedString(string: "Testing")
    let textRange = NSMakeRange(0, attributedString.length)
    let underlinedMessage = NSMutableAttributedString(attributedString: attributedString)
    underlinedMessage.addAttribute(NSAttributedStringKey.underlineStyle,
                                   value:NSUnderlineStyle.styleSingle.rawValue,
                                   range: textRange)
    label.attributedText = underlinedMessage

"


1

La risposta sopra sta causando un errore nel mio ambiente di compilazione.

Questo non funziona in Swift 4.0:

attributedText.addAttribute(NSUnderlineStyleAttributeName, 
                            value: NSUnderlineStyle.styleSingle.rawValue, 
                            range: textRange)

Prova questo invece:

attributedText.addAttribute(NSAttributedStringKey.underlineStyle,
                            value: NSUnderlineStyle.styleSingle.rawValue,
                            range: textRange)

spero che questo aiuti qualcuno.


1

// Versione Swift 4

 let attributedString  = NSMutableAttributedString(string: "Your Text Here", attributes: [NSAttributedStringKey.underlineStyle : true])

self.yourlabel.attributedText = attributedString

1

Puoi usarlo anche se vuoi ottenere solo metà dell'etichetta come sottolineato: - // Per Swift 4.0+

let attributesForUnderLine: [NSAttributedString.Key: Any] = [
            .font: UIFont(name: AppFont.sourceSansPro_Regular, size: 12) ?? UIFont.systemFont(ofSize: 11),
            .foregroundColor: UIColor.blue,
            .underlineStyle: NSUnderlineStyle.single.rawValue]

        let attributesForNormalText: [NSAttributedString.Key: Any] = [
            .font: UIFont(name: AppFont.sourceSansPro_Regular, size: 12) ?? UIFont.systemFont(ofSize: 11),
            .foregroundColor: AppColors.ColorText_787878]

        let textToSet = "Want to change your preferences? Edit Now"
        let rangeOfUnderLine = (textToSet as NSString).range(of: "Edit Now")
        let rangeOfNormalText = (textToSet as NSString).range(of: "Want to change your preferences?")

        let attributedText = NSMutableAttributedString(string: textToSet)
        attributedText.addAttributes(attributesForUnderLine, range: rangeOfUnderLine)
        attributedText.addAttributes(attributesForNormalText, range: rangeOfNormalText)
        yourLabel.attributedText = attributedText

0

Per Swift 2.3

extension UIButton {
    func underline() {
        let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
        attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: NSRange(location: 0, length: (self.titleLabel?.text!.characters.count)!))
        self.setAttributedTitle(attributedString, forState: .Normal)
    }
}

e in ViewController

@IBOutlet var yourButton: UIButton!

in ViewDidLoadMethod o nella tua funzione scrivi

yourButton.underline()

sottolineerà il titolo del tuo pulsante


0

Una classe per impostare e rimuovere la sottolineatura per i pulsanti UI di Swift 5. Spero che questo aiuti

import Foundation
   import UIKit

   class UiUtil {

       static let underlineThickness = 2
    
       class func removeUnderlineFromButton( _ button:UIButton ) {
          if let str = button.titleLabel?.attributedText {
            let attributedString = NSMutableAttributedString( attributedString: str )
            attributedString.removeAttribute(.underlineStyle, range: 
   NSRange.init(location: 0, length: attributedString.length))
            button.setAttributedTitle(attributedString, for: .normal)
         }
      }

    class func setUnderlineFromButton( _ button:UIButton ) {
        if let str = button.titleLabel?.attributedText {
            let attributedStringUnderline = NSMutableAttributedString( attributedString: 
    str  )
              attributedStringUnderline.addAttribute(
                NSAttributedString.Key.underlineStyle,
                value: underlineThickness,
                range: NSRange.init(location: 0, length: attributedStringUnderline.length)
              )
              button.setAttributedTitle(attributedStringUnderline, for: .normal)
           }
      }

   }
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.