如何从NSAttributedString swift中删除属性?

问题描述 投票:12回答:3

我在我的按钮上添加了一些属性attributedTitle

 let attr = NSMutableAttributedString(string: currTitle)

 attr.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attr.length))
 attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0,  attr.length))

 currButton?.setAttributedTitle(attr, forState: UIControlState.Normal)

单击按钮后如何从中删除NSStrikethroughStyleAttributeName?

ios swift nsattributedstring setattribute nsmutableattributedstring
3个回答
10
投票

使用removeAttribute方法:

attr.removeAttribute(NSStrikethroughStyleAttributeName, range: NSMakeRange(0, attr.length))

4
投票

非常简单。您可以从NSMutableAttributedString

使用此方法
func removeAttribute(_ name: String,
               range range: NSRange)

根据您的情况

attr.removeAttribute(NSStrikethroughStyleAttributeName , range:NSMakeRange(0, attr.length))

0
投票

在Swift 5中

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: "YourStringHere")
attributeString.removeAttribute(NSAttributedString.Key.strikethroughStyle, range: NSMakeRange(0, attributeString.length))
yourLblHere.attributedText = attributeString
© www.soinside.com 2019 - 2024. All rights reserved.