Je peux changer mon chemin pour présenter les nombres dans le champ de texte en utilisant la ligne de code suivante basée sur ce que je tape dans le champ de texte. Mais je ne peux même pas taper des nombres dans la deuxième version de mon code.Pourquoi le remplacement des caractères est-il nécessaire pour changer le texte dans le champ de texte?
Pourquoi
[let oldText = textField.text! as NSString
var newText = oldText.replacingCharacters(in: range, with: string)]
est nécessaire?
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
}
Si je le change comme ceci, ça ne marche plus.
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
}
Si la méthode shouldChangeCharactersIn met directement à jour le texte du champ de texte, alors il doit retourner faux. – rmaddy
@rmaddy merci avez-vous une idée de la raison pour laquelle la première version utilise la méthode .replacingCharacters pour changer le texte? Je veux dire qu'il y a plusieurs façons de changer le texte dans le champ de texte sans utiliser cette ligne supplémentaire. Y a-t-il un avantage à utiliser cela? –
@willianPoliciano merci! après avoir changé la valeur de retour, cela fonctionne bien avec la deuxième version. mais j'ai encore une question à voir si vous pouvez m'aider avec. Je l'adresse à la réponse à rmaddy –