如何使用SWIFT在文本字段(从右到左)输入货币格式?我有个号码,比方说0.00.当用户点击1.我们应该有0.01当用户点击2。我们应该显示0.12当用户点击3。我们应该显示1.23当用户点击4。我们应该显示12.34我怎么才能用斯威夫特做这件事?
3 回答
一只斗牛犬
TA贡献1784条经验 获得超2个赞
override func viewDidLoad() { super.viewDidLoad() textField.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged)} func myTextFieldDidChange(_ textField: UITextField) { if let amountString = textField.text?.currencyInputFormatting() { textField.text = amountString }}extension String { // formatting text for currency textField func currencyInputFormatting() -> String { var number: NSNumber! let formatter = NumberFormatter() formatter.numberStyle = .currencyAccounting formatter.currencySymbol = "$" formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 var amountWithPrefix = self // remove from String: "$", ".", "," let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive) amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "") let double = (amountWithPrefix as NSString).doubleValue number = NSNumber(value: (double / 100)) // if first number is 0 or all numbers were deleted guard number != 0 as NSNumber else { return "" } return formatter.string(from: number)! }}
桃花长相依
TA贡献1860条经验 获得超8个赞
struct DotNum { private var fraction:String = "" private var intval:String = "" init() {} mutating func enter(s:String) { if count(fraction) < 2 { fraction = s + fraction } else { intval = s + intval } } private var sFract:String { if count(fraction) == 0 { return "00" } if count(fraction) == 1 { return "0\(fraction)" } return fraction } var stringVal:String { if intval == "" { return "0.\(sFract)" } return "\(intval).\(sFract)" }}var val = DotNum()val.enter("1")val.stringVal val.enter("2")val.stringVal val.enter("3")val.stringVal val.enter("4")val.stringVal
- 3 回答
- 0 关注
- 747 浏览
添加回答
举报
0/150
提交
取消