Как я могу создать UILabel с зачеркнутым текстом?

Я хочу создать UILabel с таким текстом

введите описание изображения здесь

Как я могу это сделать? Если текст небольшой, линия также должна быть небольшой.


person Dev    schedule 30.10.2012    source источник


Ответы (20)


КОД ОБНОВЛЕНИЯ SWIFT 4

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

тогда:

yourLabel.attributedText = attributeString

Чтобы какая-то часть веревки ударялась, укажите диапазон

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

Цель-C

В iOS 6.0> UILabel поддерживает 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))

Определение:

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

Parameters List:

name: строка, определяющая имя атрибута. Ключи атрибутов могут быть предоставлены другой структурой или могут быть настраиваемыми вами. Для получения информации о том, где найти ключи атрибутов, предоставленные системой, см. Раздел обзора в Справочнике по классам NSAttributedString.

значение: значение атрибута, связанное с именем.

aRange: диапазон символов, к которому применяется указанная пара атрибут / значение.

потом

yourLabel.attributedText = attributeString;

Для lesser than iOS 6.0 versions для этого нужно 3-rd party component. Один из них - TTTAttributedLabel, другой - OHAttributedLabel.

person Paresh Navadiya    schedule 30.10.2012
comment
Для более ранней версии iOS 5.1.1, как я могу использовать стороннюю метку с атрибутами для отображения текста с атрибутами:? - person Dev; 30.10.2012
comment
Вы можете предложить хороший учебник? Ссылку, которую вы предоставили, немного сложно понять .. :( - person Dev; 30.10.2012
comment
Не могли бы вы объяснить, что мне делать для создания сторонней атрибутированной метки для ios? - person Dev; 30.10.2012
comment
Что такое @ 2? Магическое число? - person Ben Affleck; 19.05.2014
comment
Думаю, ты забыл это сделать. Вы должны использовать правильное значение из NSUnderlineStyle вместо @ 2. Я здесь немного педантичен. - person Ben Affleck; 20.05.2014
comment
Его можно выразить короче, без необходимости изменения: [[NSAttributedString alloc] initWithString:@"string" attributes:@{NSStrikethroughStyleAttributeName : @(NSUnderlineStyleSingle)}]; - person Mikkel Selsøe; 28.04.2015
comment
Для меня не работает, если я пытаюсь зачеркнуть только часть строки, а не всю. Это предназначено? И можно ли сделать так, чтобы в длинном тексте было зачеркнуто только одно слово? - person Jonauz; 13.04.2017
comment
Почему NSAttributedStringKey.strikethroughStyle: NSUnderlineStyle.styleSingleSingle.rawValue не работает в Swift 4? - person Hassan Taleb; 21.06.2017
comment
Как получить удар по центру этикетки? - person Rashid KC; 18.07.2017
comment
См. эту ветку, если у вас возникли проблемы с отображением зачеркивания. - person James Toomey; 22.09.2017

В Swift, используя перечисление для стиля одиночной зачеркивания:

let attrString = NSAttributedString(string: "Label Text", attributes: [NSStrikethroughStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
label.attributedText = attrString

Дополнительные стили зачеркивания (Не забудьте получить доступ к перечислению с помощью .rawValue):

  • NSUnderlineStyle.StyleNone
  • NSUnderlineStyle.StyleSingle
  • NSUnderlineStyle.StyleThick
  • NSUnderlineStyle.StyleDouble

Шаблоны зачеркивания (должны быть объединены оператором ИЛИ со стилем):

  • NSUnderlineStyle.PatternDot
  • NSUnderlineStyle.PatternDash
  • NSUnderlineStyle.PatternDashDot
  • NSUnderlineStyle.PatternDashDotDot

Укажите, что зачеркивание должно применяться только к словам (а не к пробелам):

  • NSUnderlineStyle.ByWord
person Chris Trevarthen    schedule 14.09.2015
comment
Up проголосовали за использование правильной константы вместо числа - person Mihai Fratu; 04.02.2016

Я предпочитаю NSAttributedString, а не NSMutableAttributedString для этого простого случая:

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

Константы для указания атрибутов NSUnderlineStyleAttributeName и NSStrikethroughStyleAttributeName строки с атрибутами:

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

Зачеркнутый в 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

Это сработало для меня как шарм.

Используйте это как расширение

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

Звоните так

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

Расширение UILabel для зачеркивания Enable / Disable.

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

Используйте это так:

   yourLabel.strikeThrough(btn.isSelected) // true OR false
person Purnendu roy    schedule 07.05.2018
comment
Вы случайно не знаете, что StrikeThrough не удаляется? Аналогично forum.developer.apple.com/thread/121366. - person Jeroen; 21.04.2020

SWIFT-КОД

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

тогда:

yourLabel.attributedText = attributeString

Благодаря ответ принца;)

person pekpon    schedule 25.01.2015

SWIFT 4

    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text Goes Here")
    attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0, attributeString.length))
    self.lbl_productPrice.attributedText = attributeString

Другой способ - использовать строковое расширение
Расширение

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

Вызов функции. Используется так

testUILabel.attributedText = "Your Text Goes Here!".strikeThrough()

Кредит для @Yahya - обновление, декабрь 2017 г.
Кредит для @kuzdu - обновление, август 2018 г.

person Muhammad Asyraf    schedule 08.12.2017
comment
У меня не работает. Ответ Пурненду Роя сработал для меня. Единственная разница в том, что вы проходите value 0 и проходите Пурненду рой value: NSUnderlineStyle.styleSingle.rawValue. - person kuzdu; 27.07.2018
comment
@kuzdu забавная вещь, что мой ответ был еще в декабре 2017 года, он работает, тогда он просто скопировал мой код и добавил NSUnderlineStyle.styleSingle.rawValue ^ - ^ Но нет проблем, я обновлю этот ответ, чтобы вы были счастливы - person Muhammad Asyraf; 01.08.2018

Вы можете сделать это в IOS 6 с помощью NSMutableAttributedString.

NSMutableAttributedString *attString=[[NSMutableAttributedString alloc]initWithString:@"$198"];
[attString addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:2] range:NSMakeRange(0,[attString length])];
yourLabel.attributedText = attString;
person Ameet Dhas    schedule 30.10.2012

Вычеркнуть текст UILabel в Swift iOS. Пожалуйста, попробуйте, это работает для меня

let attributedString = NSMutableAttributedString(string:"12345")
                      attributedString.addAttribute(NSAttributedStringKey.baselineOffset, value: 0, range: NSMakeRange(0, attributedString.length))
                      attributedString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSNumber(value: NSUnderlineStyle.styleThick.rawValue), range: NSMakeRange(0, attributedString.length))
                      attributedString.addAttribute(NSAttributedStringKey.strikethroughColor, value: UIColor.gray, range: NSMakeRange(0, attributedString.length))

 yourLabel.attributedText = attributedString

Вы можете изменить свой "strikethroughStyle", например styleSingle, styleThick, styleDouble  введите описание изображения здесь

person Karthick C    schedule 25.12.2017

Swift 5

extension String {

  /// Apply strike font on text
  func strikeThrough() -> NSAttributedString {
    let attributeString = NSMutableAttributedString(string: self)
    attributeString.addAttribute(
      NSAttributedString.Key.strikethroughStyle,
      value: 1,
      range: NSRange(location: 0, length: attributeString.length))

      return attributeString
     }
   }

Пример:

someLabel.attributedText = someText.strikeThrough()
person Vladimir Pchelyakov    schedule 25.07.2019
comment
Разница между значением: 1 и значением: 2 - person iOS; 18.09.2019
comment
Значение @iOS - это толщина линии, перечеркивающей текст. Чем больше значение, тем толще линия, перечеркивающая текст. - person Vladimir Pchelyakov; 18.09.2019
comment
@VladimirPchelyakov Нет. Значение соответствует NSUnderlineStyle rawValue (NSNumber). 1 = одинарный, 2 = толстый, 9 = двойной, и есть много других стилей между толстым и двойным - person Leo Dabus; 26.10.2020

Для тех, кто смотрит, как это сделать в ячейке tableview (Swift), вы должны установить .attributeText следующим образом:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("TheCell")!

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

    cell.textLabel?.attributedText =  attributeString

    return cell
    }

Если вы хотите удалить зачеркивание, сделайте это, иначе оно останется !:

cell.textLabel?.attributedText =  nil
person Micro    schedule 07.06.2016

Swift 4.2

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: product.price)

attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, attributeString.length))

lblPrice.attributedText = attributeString
person Harshal Valanda    schedule 30.10.2018

Я могу опоздать на вечеринку.

В любом случае, я знаю NSMutableAttributedString, но недавно я достиг той же функциональности с немного другим подходом.

  • Я добавил UIView с высотой = 1.
  • Сопоставил начальные и конечные ограничения UIView с начальными и конечными ограничениями метки
  • Выровнял UIView по центру ярлыка

После выполнения всех вышеперечисленных шагов мой ярлык, UIView и его ограничения выглядели так, как показано на рисунке ниже.

введите здесь описание изображения

person user7420795    schedule 22.04.2020
comment
умное решение ???? - person Dania Delbani; 27.07.2020

Используйте код ниже

NSString* strPrice = @"£399.95";

NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc] initWithString:strPrice];

[finalString addAttribute: NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger: NSUnderlineStyleSingle] range: NSMakeRange(0, [titleString length])];
self.lblOldPrice.attributedText = finalString;   
person Hardik Thakkar    schedule 06.05.2015

Измените свойство текста на присвоенное, выберите текст и щелкните правой кнопкой мыши, чтобы получить свойство шрифта. Щелкните зачеркивание. Снимок экрана

person Jayakrishnan    schedule 02.07.2019

В iOS 10.3 есть проблема с отрисовкой исправлений зачеркивания строки путем добавления NSBaselineOffsetAttributeName, как описано здесь, в атрибутивную строку, возвращает зачеркнутую строку. Переопределение drawText: in: может быть медленным, особенно для ячеек представления коллекции или представления таблицы.

Одно решение - Добавить вид для рендеринга линии.

Второй золь -

attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
attributeString.addAttribute(NSAttributedString.Key.baselineOffset, value: 2, range: NSMakeRange(0, attributeString.length))```
person TheCodeTalker    schedule 21.08.2020

Swift 4 и 5

extension NSAttributedString {

    /// Returns a new instance of NSAttributedString with same contents and attributes with strike through added.
     /// - Parameter style: value for style you wish to assign to the text.
     /// - Returns: a new instance of NSAttributedString with given strike through.
     func withStrikeThrough(_ style: Int = 1) -> NSAttributedString {
         let attributedString = NSMutableAttributedString(attributedString: self)
         attributedString.addAttribute(.strikethroughStyle,
                                       value: style,
                                       range: NSRange(location: 0, length: string.count))
         return NSAttributedString(attributedString: attributedString)
     }
}

Пример

let example = NSAttributedString(string: "440").withStrikeThrough(1)
myLabel.attributedText = example

Результаты

введите описание изображения здесь

person Rashid Latif    schedule 10.05.2020

Swift 5 - короткая версия

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

yourLabel.attributedText = attrString
person Dan Developer    schedule 30.04.2021

Для тех, кто сталкивается с проблемой с предупреждением о многострочном тексте

    let attributedString = NSMutableAttributedString(string: item.name!)
    //necessary if UILabel text is multilines
    attributedString.addAttribute(NSBaselineOffsetAttributeName, value: 0, range: NSMakeRange(0, attributedString.length))
     attributedString.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue), range: NSMakeRange(0, attributedString.length))
    attributedString.addAttribute(NSStrikethroughColorAttributeName, value: UIColor.darkGray, range: NSMakeRange(0, attributedString.length))

    cell.lblName.attributedText = attributedString
person Spydy    schedule 10.09.2017

Создайте расширение String и добавьте метод ниже

static func makeSlashText(_ text:String) -> NSAttributedString {


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

return attributeString 

}

затем используйте для своего ярлыка, как это

yourLabel.attributedText = String.makeSlashText("Hello World!")
person Josh Gray    schedule 26.12.2017

Это тот, который вы можете использовать в Swift 4, потому что NSStrikethroughStyleAttributeName был изменен на NSAttributedStringKey.strikethroughStyle

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "Your Text")

attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))

self.lbl.attributedText = attributeString
person vikram    schedule 11.08.2018