我在静态单元格 tableView 上有一个名为 textField
的 UItextField
。该字段包含货币金额 - 例如“$10,000.00”。
编辑该金额时,货币和千位分组符号有点碍事。因此,当该字段成为第一响应者时,我想删除它们。
我在 textFieldShouldBeginEditing
中执行此操作。
我第一次这样做时,一切正常。 textField
的内容被重新格式化,没有货币和千位组分隔符。
在 textFieldDidEndEditing
上,我再次将值重新格式化为正确的货币字符串。这也有效。
当我第二次重新进入该字段时出现问题。在调试时我可以看到 textField.text
已经变成了没有货币符号和分组符号的字符串,但是显示器没有显示。虽然第一次成功了!第二次看起来屏幕上的内容与调试器看到的值不匹配。
我试过这样的事情:
- tableView.beginUpdates(); tableView.endUpdates()
- textView.setNeedsDisplay
...但这不起作用。
所以我将 textFieldShouldBeginEditing
中删除货币格式的代码复制到新的委托(delegate)方法 textFieldDidBeginEditing
。
然后一切正常。我可以多次点击其他控件并返回到 textField,每次输入时控件都会丢失其格式,并在失去焦点后恢复为格式化的货币字符串。
所以我决定删除方法textFieldShouldBeginEditing
。但是后来事情又坏了!看起来我必须同时实现 textFieldShouldBeginEditing
和 textFieldDidBeginEditing
才能准备 textField
的内容供用户编辑?
这是一个错误吗?
extension Double {
public func doubleToString(numberStyle: NumberFormatter.Style, decimals: Int, withThousandSeparator: Bool) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = numberStyle
numberFormatter.maximumFractionDigits = decimals
if !withThousandSeparator {
numberFormatter.groupingSeparator = ""
}
return numberFormatter.string(from: NSNumber(value: self)) ?? ""
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField === self.textField {
textField.text = amount.doubleToString(numberStyle: .decimal, decimals: 2, withThousandSeparator: false)
}
}
最佳答案
你应该尝试 textField 的文本更改事件,附上下面的代码:
在 textField 上添加目标以更改文本:
self.textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
textField 的文本更改函数:
func textFieldDidChange(_ textField: UITextField)
{
if textField === self.textField
{
//try formatting here
}
}
关于ios - 意外行为文本 textFieldShouldBeginEditing/textFieldDidBeginEditing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53326641/