Mah*_*esh 6 iphone nsattributedstring uilabel ios swift
我正在使用一个标签,该标签显示具有删除线属性的产品的旧价格.我试图为属性字符串设置删除线属性,但无法获得实际结果.
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
Run Code Online (Sandbox Code Playgroud)
有没有办法同时为字符串设置货币格式化程序和删除线属性?
试试这个并看看(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
}
Run Code Online (Sandbox Code Playgroud)
结果:
₹1,000.00
对于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
Run Code Online (Sandbox Code Playgroud)
小智 1
迅速
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "Your Text")
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))
Run Code Online (Sandbox Code Playgroud)