我正在使用一个标签,该标签显示具有删除线属性的产品的旧价格。我正在尝试为属性字符串设置删除线属性,但无法获得实际结果。
let price = 1000.0
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
currencyFormatter.currencyCode = "INR"
let priceInINR = currencyFormatter.string(from: price as NSNumber)
let attributedString = NSMutableAttributedString(string: priceInINR!)
attributedString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributedString.length))
self.oldPriceLabel.attributedText = attributedString
有什么办法可以同时为一个字符串设置货币格式化程序和删除线属性?
最佳答案
试试看,看看(兼容Swift 3和4):
@IBOutlet var oldPriceLabel: UILabel!
func strikeOnLabel() {
let price = 1000.0
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
currencyFormatter.currencyCode = "INR"
let priceInINR = currencyFormatter.string(from: price as NSNumber)
let attributedString = NSMutableAttributedString(string: priceInINR!)
// Swift 4.2 and above
attributedString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributedString.length))
// Swift 4.1 and below
attributedString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 2, range: NSMakeRange(0, attributedString.length))
oldPriceLabel.attributedText = attributedString
}
结果:
对于Swift 2:
let price = 1000.0
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
currencyFormatter.currencyCode = "INR"
let priceInINR = currencyFormatter.string(from: price as NSNumber)
let attributedString = NSMutableAttributedString(string: priceInINR!)
// Swift 4.2 and above
attributedString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributedString.length))
// Swift 4.1 and below
attributedString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributedString.length))
self.oldPriceLabel.attributedText = attributedString
关于ios - 在Swift 3中为货币格式的字符串设置删除线属性文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45960149/