首页 > 解决方案 > 如何在 iOS 中将文本字段分隔为数字格式的逗号?

问题描述

我希望数字为 12,345,678,所以当我在文本字段中输入时,它就会出现。文本字段的最大输入值为 8 位。

我使用了以下代码,但输入 7 位数字后无法清除该号码。

我如何解决它?

override func viewDidLoad() {
    myTextfield.delegate = self
    self.myTextfield.keyboardType = .numberPad

    myTextfield.addTarget(self, action:#selector(textFieldValDidChange), for: .editingChanged)
}

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    return range.location < 8
}

@objc func textFieldValDidChange(_ textField: UITextField) {
    let formatter = NumberFormatter()
    formatter.numberStyle = NumberFormatter.Style.decimal
    if textField.text!.count >= 1 {
        let number = Double(textField.text!.replacingOccurrences(of: ",", with: ""))
        let result = formatter.string(from: NSNumber(value: number!))
        textField.text = result!
    }
}

标签: iosswiftuitextfield

解决方案


public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return range.location < 10
    }

8 位数字加 2 个逗号,即 10 个字符(最后一个索引为 9)。


推荐阅读