Я хочу создать UILabel
с таким текстом
Как я могу это сделать? Если текст небольшой, линия также должна быть небольшой.
Я хочу создать UILabel
с таким текстом
Как я могу это сделать? Если текст небольшой, линия также должна быть небольшой.
КОД ОБНОВЛЕНИЯ 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.
[[NSAttributedString alloc] initWithString:@"string" attributes:@{NSStrikethroughStyleAttributeName : @(NSUnderlineStyleSingle)}];
- person Mikkel Selsøe; 28.04.2015
В Swift, используя перечисление для стиля одиночной зачеркивания:
let attrString = NSAttributedString(string: "Label Text", attributes: [NSStrikethroughStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue])
label.attributedText = attrString
Дополнительные стили зачеркивания (Не забудьте получить доступ к перечислению с помощью .rawValue):
Шаблоны зачеркивания (должны быть объединены оператором ИЛИ со стилем):
Укажите, что зачеркивание должно применяться только к словам (а не к пробелам):
Я предпочитаю 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;
Зачеркнутый в 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
SWIFT-КОД
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "Your Text")
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))
тогда:
yourLabel.attributedText = attributeString
Благодаря ответ принца;)
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 г.
value
0
и проходите Пурненду рой value: NSUnderlineStyle.styleSingle.rawValue
.
- person kuzdu; 27.07.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;
Вычеркнуть текст 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
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()
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
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
Я могу опоздать на вечеринку.
В любом случае, я знаю NSMutableAttributedString
, но недавно я достиг той же функциональности с немного другим подходом.
После выполнения всех вышеперечисленных шагов мой ярлык, UIView и его ограничения выглядели так, как показано на рисунке ниже.
Используйте код ниже
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;
Измените свойство текста на присвоенное, выберите текст и щелкните правой кнопкой мыши, чтобы получить свойство шрифта. Щелкните зачеркивание.
В 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))```
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
Результаты
Swift 5 - короткая версия
let attrString = NSAttributedString(string: "Label Text", attributes: [NSAttributedString.Key.strikethroughStyle: NSUnderlineStyle.single.rawValue])
yourLabel.attributedText = attrString
Для тех, кто сталкивается с проблемой с предупреждением о многострочном тексте
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
Создайте расширение 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!")
Это тот, который вы можете использовать в 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
NSAttributedString
иUILabel attributedText
. - person rmaddy   schedule 30.10.2012