如何创建带有删除线文本的UILabel?

146
我想创建一个 UILabel,其中文本内容如下所示:

enter image description here

当文本较小时,行也应该较小。如何实现这个功能?

1
可能是重复问题:http://stackoverflow.com/questions/10550732/font-with-strike-through-it - mopsled
如果您只需要支持iOS 6,则可以使用“NSAttributedString”和“UILabel attributedText”属性来实现此目的。 - rmaddy
是否可以取消按钮文本的删除线? - SCS
21个回答

261

SWIFT 5 更新代码

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

然后:

yourLabel.attributedText = attributeString

如果想让字符串的某一部分突出显示,则需提供其范围。

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

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

参数列表:

name:指定属性名称的字符串。属性键可以由另一个框架提供,也可以是您定义的自定义键。有关查找系统提供的属性键的信息,请参阅NSAttributedString Class Reference中的概述部分。

value:与名称相关联的属性值。

aRange:指定属性/值对适用的字符范围。

然后

yourLabel.attributedText = attributeString;

对于低于 iOS 6.0 版本的设备,您需要使用第三方组件才能实现此操作。其中之一是 TTTAttributedLabel,另一个是 OHAttributedLabel


对于 iOS 5.1.1 及更低版本,我该如何使用第三方属性标签来显示属性文本? - Dev
@2是什么? 魔数吗? - pronebird
9
我猜你忘记提交了。你应该使用NSUnderlineStyle中的正确值,而不是@2。我在这方面有点过于追求完美。 - pronebird
可以更简洁地表达,而无需可变性:[[NSAttributedString alloc] initWithString:@"string" attributes:@{NSStrikethroughStyleAttributeName : @(NSUnderlineStyleSingle)}]; - Mikkel Selsøe
如何在标签中心获得横线? - Rashid KC
显示剩余5条评论

61

在Swift中,使用单划线删除线样式:

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

额外的删除线样式(请记得使用 .rawValue):

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

删除线模式(与样式使用 OR 运算):

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

指定删除线仅应应用于单词(而不是空格)之间:

  • .byWord

2
使用正确的常量而非数字得到了点赞。 - Mihai Fratu

38

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扩展。

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

1
你知道去除StrikeThrough的解决方案吗?类似于https://forums.developer.apple.com/thread/121366。 - Jeroen

36

在这个简单的情况下,我更喜欢使用 NSAttributedString 而不是 NSMutableAttributedString

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

用于指定带属性字符串的NSUnderlineStyleAttributeNameNSStrikethroughStyleAttributeName属性的常量:


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

23

SWIFT代码

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

那么:

yourLabel.attributedText = attributeString

感谢Prince的回答 ;)


16

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年12月更新
感谢@kuzdu - 2018年8月更新

Credit to @kuzdu - updated in August 2018


对我不起作用。Purnendu Roy的答案对我有用。唯一的区别是你传递value 0,而Purnendu Roy传递value: NSUnderlineStyle.styleSingle.rawValue - kuzdu
@kuzdu 有趣的是,我的答案早在2017年12月就已经回答了,当时它是有效的。他只是复制了我的代码并添加了NSUnderlineStyle.styleSingle.rawValue ^-^ 但没关系,我会更新这个答案,只是为了让你开心。 - Muhammad Asyraf

10

在iOS的Swift中划掉 UILabel 的文本。请尝试这个方法,它对我有用。

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

你可以像styleSingle、styleThick、styleDouble一样改变你的"strikethroughStyle" 进入图片描述


9

您可以在IOS 6中使用NSMutableAttributedString完成此操作。

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

6

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()

值为1和值为2之间的差异。 - Naresh
2
@iOS 值是删除线的粗细。值越大,划掉文本的线就越粗。 - Vladimir Pchelyakov
@VladimirPchelyakov 不是的。该值对应于 NSUnderlineStyle 的 rawValue(NSNumber)。1 = 单线,2 = 粗线,9 = 双线,还有许多粗线和双线之间的其他样式。 - Leo Dabus

4

如果有人想在表格视图单元格中实现此操作(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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接