我有一个输入文本,用户在其中输入金额。我现在遇到的问题是,如果用户输入值1000
,我希望它以1,000
的形式显示在文本字段中,而当我想获取textField
的值时,我希望能够收回1000
。我如何才能做到这一点,因为我尝试过的代码只能帮助打印1,000
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.numberStyle = .decimal
return formatter
}()
}
extension Integer{
var formattedWithSeparator: String {
return Formatter.withSeparator.string(for: self) ?? ""
}
}
let myInt = 1234500
let myIntString = myInt.formattedWithSeparator // "1,234,500"
答案 0 :(得分:0)
使用此代码,您会得到它
导入UIKit
class IntegerField: UITextField {
var lastValue = 0
let maxValue = 1_000_000_000
var amount: Int {
if let newValue = Int(string.digits), newValue < maxValue {
lastValue = newValue
} else if !hasText {
lastValue = 0
}
return lastValue
}
override func didMoveToSuperview() {
textAlignment = .right
keyboardType = .numberPad
text = Formatter.decimal.string(for: amount)
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
@objc func editingChanged(_ textField: UITextField) {
text = Formatter.decimal.string(for: amount)
}
}
extension NumberFormatter {
convenience init(numberStyle: Style) {
self.init()
self.numberStyle = numberStyle
}
}
struct Formatter {
static let decimal = NumberFormatter(numberStyle: .decimal)
}
extension UITextField {
var string: String { return text ?? "" }
}
extension String {
private static var digitsPattern = UnicodeScalar("0")..."9"
var digits: String {
return unicodeScalars.filter { String.digitsPattern ~= $0 }.string
}
}
extension Sequence where Iterator.Element == UnicodeScalar {
var string: String { return String(String.UnicodeScalarView(self)) }
}
答案 1 :(得分:-1)
您可以这样操作:
extension Int {
var intString = "\(self)"
let lenght = intString.count
for i in 0...lenght {
if i % 3 == 0 && i != 0 {
intString.insert(",", at: String.Index(encodedOffset: lenght - i))
}
}
if intString.first == "," {
intString.removeFirst()
}
return intString
}
和
extension String {
func removeCommas() -> Int {
var copy = String()
for character in self {
if character != "," {
copy.append(character)
}
}
if let int = Int(copy) {
return int
} else {
return 0
}
}
}
然后您可以将这些函数与字符串/ int一起使用:
let string = 1435.addCommas() //Return "1,435"
let int = "1,234,567".removeCommas() //Return 1234567
因此,当viewField中的textField文本更改时,您可以调用一个函数:
@IBAction func textChanged(_ sender: UITextField) {
if textField.text != "" {
myIntNumber = textField.text!.removeCommas()
textField.text = myIntNumber.addCommas()
}
}