为数字添加逗号分隔符,在键入时每隔三位数字

时间:2018-01-24 11:59:06

标签: ios xcode

我尝试使用swift 4.0和Xcode 9在为iOS应用程序键入时立即为文本字段中输入的每三位数添加一个逗号分隔符。 到目前为止,我已将这些代码行添加到我的viewdidload方法中:

     self.mainTextField.delegate = self

  self.mainTextField(self, action: #selector(self.textFieldDidChange(textField:)), for: .editingChanged)

我还将此功能添加到我的视图控制器:

func textFieldDidChange(textField: UITextField) {
        if textField == self.mainTextField {

            // Some locales use different punctuations.
            var textFormatted = textField.text?.replacingOccurrences(of: ",", with: "")
            textFormatted = textFormatted?.replacingOccurrences(of: ".", with: "")

            let numberFormatter = NumberFormatter()
            numberFormatter.numberStyle = .decimal
            if let text = textFormatted, let textAsInt = Int(text) {
                textField.text = numberFormatter.string(from: NSNumber(value: textAsInt))
            }
        }
    }

但我一直收到来自Xcode的错误: 无法调用非功能类型的值' UITextField' 在这一行:

self.mainTextField(self,action:#selector(self.textFieldDidChange(textField :)),for:.editingChanged)

1 个答案:

答案 0 :(得分:1)

您忘记了方法名称addTarget。而不是

self.mainTextField(self, action: #selector(self.textFieldDidChange(textField:)), for: .editingChanged)

使用

self.mainTextField.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: .editingChanged)