我有一个标签:
label.numberOfLines = 0
我试图通过以下方式将此标签的文字删除:
let index: NSMutableAttributedString = NSMutableAttributedString(string: label.text!)
index.addAttributes([NSStrikethroughStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSStrikethroughColorAttributeName: UIColor.red], range: NSMakeRange(0, index.length))
label.textColor = UIColor.red
label.attributedText = index
属性字符串是否适用于多行或使用numberOfLines设置为0的标签?如果是这样,如何使多行文字删除?
答案 0 :(得分:7)
如果在之前添加NSBaselineOffsetAttributeName,则可以正常使用多行:
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: (object?.title)!)
attributeString.addAttribute(NSBaselineOffsetAttributeName, value: 0, range: NSMakeRange(0, attributeString.length))
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))
答案 1 :(得分:1)
您的代码应该是,
let index: NSMutableAttributedString = NSMutableAttributedString(string: lbl.text!)
index.addAttributes([NSStrikethroughStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue, NSStrikethroughColorAttributeName: UIColor.red], range: NSMakeRange(0, index.length))
lbl.textColor = UIColor.red
lbl.attributedText = index
因为index
是你的可变字符串!不是标题!
并且您不能将strike through
与multi line
标签一起使用。
如果您想要多行效果strike through
,那么您可以使用UITextView
代替标签!
答案 2 :(得分:0)
写出来,
self.label.numberOfLines = 0
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: self.label.text!)
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))
self.label.attributedText = attributeString
在我的最后工作。
答案 3 :(得分:0)
我想出了两个解决方案。它们基于@SivajeeBattina答案。
首先是在http://adamvarga.com/strike/的帮助下删除文字。
private func returnStrikedOutTextFromString(_ str: String) -> String {
var newString = ""
let normal = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя "
let strikethrough = "А̶Б̶В̶Г̶Д̶Е̶Ё̶Ж̶З̶И̶Й̶К̶Л̶М̶Н̶О̶П̶Р̶С̶Т̶У̶Ф̶Х̶Ц̶Ч̶Ш̶Щ̶Ъ̶Ы̶Ь̶Э̶Ю̶Я̶а̶б̶в̶г̶д̶е̶ё̶ж̶з̶и̶й̶к̶л̶м̶н̶о̶п̶р̶с̶т̶у̶ф̶х̶ц̶ч̶ш̶щ̶ъ̶ы̶ь̶э̶ю̶я̶ ̶̶"
for i in 0..<str.characters.count {
let range: Range<String.Index> =
normal.range(of: str
.substring(to: str.index(str.startIndex, offsetBy: i + 1))
.substring(from: str.index(str.startIndex, offsetBy: i)))!
let index: Int = normal.distance(from: normal.startIndex, to: range.lowerBound)
newString = String(format: "%@%@", newString,
NSLocalizedString(strikethrough
.substring(to: strikethrough.index(strikethrough.startIndex, offsetBy: index + 1))
.substring(from: strikethrough.index(strikethrough.startIndex, offsetBy: index)),
comment: ""))
}
return newString
}