【发布时间】:2018-01-25 01:41:45
【问题描述】:
我正在尝试为用户在使用 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)
【问题讨论】:
-
self.mainTextField(self, ...=>self.mainTextField.addTarget(self, ...? -
很棒的解决方案 - 我已经寻找这个解决方案好几天了。谢谢你。不过有一个问题 - 我也希望能够将点(。)作为十进制。
-
@SiphoKoza 你可以自己定义 numberFormatter numberFormatter.numberStyle = .decimal numberFormatter.groupingSeparator = "." numberFormatter.groupingSize = 3 numberFormatter.usesGroupingSeparator = true numberFormatter.decimalSeparator = "."
-
@mdehghani 谢谢。它运作良好。