我可以根据我在文本字段中输入的内容,使用以下代码行来改变我在文本字段中显示数字的方式。但是我甚至无法在我的代码的第二个版本中输入数字。为什么replaceCharacters更改文本字段中的文本所必需的?
为什么
[let oldText = textField.text! as NSString
var newText = oldText.replacingCharacters(in: range, with: string)]
是必要的吗?
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let oldText = textField.text! as NSString
var newText = oldText.replacingCharacters(in: range, with: string)
var newTextString = String(newText)
let digits = CharacterSet.decimalDigits
var digitText = ""
for c in (newTextString?.unicodeScalars)! {
if digits.contains(UnicodeScalar(c.value)!) {
digitText.append("\(c)")
}
}
// Format the new string
if let numOfPennies = Int(digitText) {
newText = "$" + self.dollarStringFromInt(numOfPennies) + "." + self.centsStringFromInt(numOfPennies)
} else {
newText = "$0.00"
}
textField.text = newText
return false
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.text!.isEmpty {
textField.text = "$0.00"
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true;
}
func dollarStringFromInt(_ value: Int) -> String {
return String(value/100)
}
func centsStringFromInt(_ value: Int) -> String {
let cents = value % 100
var centsString = String(cents)
if cents < 10 {
centsString = "0" + centsString
}
return centsString
}
如果我像这样改变它,它不再工作。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var newText = textField.text
let digits = CharacterSet.decimalDigits
var digitText = ""
for c in (newText?.unicodeScalars)! {
if digits.contains(UnicodeScalar(c.value)!) {
digitText.append("\(c)")
}
}
// Format the new string
if let numOfPennies = Int(digitText) {
newText = "$" + self.dollarStringFromInt(numOfPennies) + "." + self.centsStringFromInt(numOfPennies)
} else {
newText = "$0.00"
}
textField.text = newText
return false
}
如果shouldChangeCharactersIn方法直接更新文本字段的文本,那么它必须返回false。 – rmaddy
@rmaddy谢谢你有什么想法为什么第一个版本使用.replacingCharacters方法来改变文本?我的意思是有很多方法可以在不使用额外的行的情况下更改文本字段中的文本。使用它有什么好处吗? –
@willianPoliciano谢谢!在改变返回值后,它适用于第二个版本。但仍然有一个问题,看看你能否帮助我。我在回复rmaddy时解决了这个问题 –