148 votes

Comment créer un UILabel avec du texte barré ?

Je veux créer un UILabel dans lequel le texte est le suivant

enter image description here

Comment puis-je le faire ? Lorsque le texte est petit, la ligne doit également être petite.

265voto

Prince Points 16165

CODE DE MISE À JOUR DE SWIFT 5

let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "Your Text")
    attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSRange(location: 0, length: attributeString.length))

alors :

yourLabel.attributedText = attributeString

Faire en sorte qu'une partie de la corde frappe puis fournisse une portée.

let somePartStringRange = (yourStringHere as NSString).range(of: "Text")
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: somePartStringRange)

Objectif-C

En iOS 6.0 > UILabel soutient NSAttributedString

NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Your String here"];
[attributeString addAttribute:NSStrikethroughStyleAttributeName
                        value:@2
                        range:NSMakeRange(0, [attributeString length])];

Swift

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your String here")
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

Définition :

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)aRange

Parameters List:

nom : Une chaîne de caractères spécifiant le nom de l'attribut. Les clés d'attribut peuvent être fournies par un autre framework ou peuvent être personnalisées et définies par vous. Pour savoir où trouver les clés d'attribut fournies par le système, consultez la section Vue d'ensemble dans la référence de la classe NSAttributedString.

valeur : La valeur de l'attribut associé au nom.

aRange : La plage de caractères à laquelle s'applique la paire attribut/valeur spécifiée.

Puis

yourLabel.attributedText = attributeString;

Pour lesser than iOS 6.0 versions vous avez besoin 3-rd party component pour le faire. L'une d'entre elles est TTTAttributedLabel un autre est OHAttributedLabel .

61voto

Chris Trevarthen Points 2547

Dans Swift, en utilisant le style de ligne barré simple :

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

Styles de biffures supplémentaires ( N'oubliez pas d'utiliser l'option .rawValue ) :

  • .none
  • .single
  • .thick
  • .double

Motifs de biffure (à utiliser avec le style) :

  • .patternDot
  • .patternDash
  • .patternDashDot
  • .patternDashDotDot

Spécifiez que le barré ne doit être appliqué qu'aux mots (et non aux espaces) :

  • .byWord

38voto

Purnendu roy Points 510

Barré dans Swift 5.0

let attributeString =  NSMutableAttributedString(string: "Your Text")
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle,
                                     value: NSUnderlineStyle.single.rawValue,
                                         range: NSMakeRange(0, attributeString.length))
self.yourLabel.attributedText = attributeString

Ça a marché pour moi comme un charme.

Utilisez-le comme extension

extension String {
    func strikeThrough() -> NSAttributedString {
        let attributeString =  NSMutableAttributedString(string: self)
        attributeString.addAttribute(
            NSAttributedString.Key.strikethroughStyle,
               value: NSUnderlineStyle.single.rawValue,
                   range:NSMakeRange(0,attributeString.length))
        return attributeString
    }
}

Appelez comme ceci

myLabel.attributedText = "my string".strikeThrough()

Extension UILabel pour le barré Activer/Désactiver.

extension UILabel {

func strikeThrough(_ isStrikeThrough:Bool) {
    if isStrikeThrough {
        if let lblText = self.text {
            let attributeString =  NSMutableAttributedString(string: lblText)
            attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0,attributeString.length))
            self.attributedText = attributeString
        }
    } else {
        if let attributedStringText = self.attributedText {
            let txt = attributedStringText.string
            self.attributedText = nil
            self.text = txt
            return
        }
    }
    }
}

Utilisez-le comme ceci :

   yourLabel.strikeThrough(btn.isSelected) // true OR false

36voto

Kjuly Points 15089

Je préfère NSAttributedString plutôt que NSMutableAttributedString pour ce cas simple :

NSAttributedString * title =
    [[NSAttributedString alloc] initWithString:@"$198"
                                    attributes:@{NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle)}];
[label setAttributedText:title];

Constantes permettant de spécifier à la fois le NSUnderlineStyleAttributeName y NSStrikethroughStyleAttributeName les attributs d'une chaîne attribuée :

typedef enum : NSInteger {  
  NSUnderlineStyleNone = 0x00,  
  NSUnderlineStyleSingle = 0x01,  
  NSUnderlineStyleThick = 0x02,  
  NSUnderlineStyleDouble = 0x09,  
  NSUnderlinePatternSolid = 0x0000,  
  NSUnderlinePatternDot = 0x0100,  
  NSUnderlinePatternDash = 0x0200,  
  NSUnderlinePatternDashDot = 0x0300,  
  NSUnderlinePatternDashDotDot = 0x0400,  
  NSUnderlineByWord = 0x8000  
} NSUnderlineStyle;

23voto

pekpon Points 761

CODE SWIFT

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text")
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

alors :

yourLabel.attributedText = attributeString

Merci à Réponse du prince ;)

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X