答案 0 :(得分:3)
使用attributeString
截图
代码
NSDictionary * attribtues = @{NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle),
NSStrikethroughColorAttributeName:[UIColor redColor]};
NSAttributedString * attr = [[NSAttributedString alloc] initWithString:@"label" attributes:attribtues];
self.label.attributedText = attr;
答案 1 :(得分:2)
Swift4的@krunal答案中的更新功能
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
}
}
与要调用的功能相同
yourLabel.attributedText = "yourString".strikeThrough()
答案 2 :(得分:1)
如果想使用 UILabel 扩展
extension UILabel {
func strikeThroughText() {
let attributeString = NSMutableAttributedString(string: self.text ?? "")
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0,attributeString.length))
self.attributedText = attributeString
}
}
答案 3 :(得分:0)
答案 4 :(得分:0)
以程序方式使用以下代码
首选使用扩展程序:
extension String {
func strikeThrough() -> NSAttributedString {
let attributeString = NSMutableAttributedString(string: self)
attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSUnderlineStyle.styleSingle.rawValue, range: NSMakeRange(0,attributeString.length))
return attributeString
}
}
并调用此函数
myLabel.attributedText = "my string".strikeThrough()
结果看起来像这样。