Come posso ottenere un metodo textDidChange per un UITextField? Devo chiamare un metodo ogni volta che viene apportata una modifica a un campo di testo. È possibile? Grazie!Come posso ottenere un metodo textDidChange (come per un UISearchBar) per un UITextField?
risposta
è possibile impostare un delegato e utilizzare
- (BOOL) textField: (UITextField *) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString *) string;
È possibile utilizzare UITextFieldTextDidChangeNotification
per chiamare un metodo ogni volta che il campo di testo cambia. Aggiungi questo al vostro init
:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
L'advantag Per questo metodo, la risposta di Ben è che puoi essere avvisato * dopo * il testo cambia. Se usi 'shouldChangeCharactersInRange' devi provare a calcolare come apparirà la stringa una volta che la modifica è stata permessa. – Andrew
@Andrew - Lo dici come se fosse difficile. Basta usare '[[textField.text mutableCopy] replaceCharactersInRange: range withString: string] 'per ottenere la stringa post-cambiamento. – ArtOfWarfare
In realtà, non è proprio così facile. È necessario aggiungere una variabile locale per mantenere NSMutableString restituito da '[[textField.text] mutableCopy]', quindi utilizzare il metodo replace su quella variabile locale, quindi fare ciò che si desidera con la variabile locale, solo perché restituisce invece void rispetto alla stringa modificata. – ArtOfWarfare
Sviluppando ulteriormente la risposta di Ben Gottlieb sopra, usando textField shouldChangeCharactersInRange è grande, ma ha lo svantaggio che alcune cose possono accadere con un ritardo di un carattere.
Ad esempio, se si chiama il sotto per avvisare l'utente quando non è presente alcun testo, viene chiamato il carattere dopo aver inserito un carattere e non è più vuoto.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (!textField.text.length) {
// Do something with empty textfield
}
return YES;
}
Il metodo seguito consente di ottenere un cambiamento rudimentale accadendo nel vostro textField. Sebbene non sia così diretto come una NSNotification, ti consente comunque di usare metodi simili con diversi campi di testo e quindi è una cosa molto utile da usare quando cerchi di ottenere cambiamenti di caratteri specifici nel tuo campo di testo.
Il codice sotto fissa il ritardo carattere
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// This means it updates the name immediately
NSString * newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
textField.placeholder = newString.length ? @"" : @"Name";
return YES;
}
Per questo codice viene utilizzato per aggiungere un segnaposto per un UITextField quando non c'è testo nella textField
Swift Soluzione
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
return true
}
È anche possibile selezionare un target & per l'evento UIControlEventEditingChanged
. Per esempio:
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]
Si noti che questo sarà chiamato solo per utenti cambiamenti avviati al campo di testo e non verrà chiamato automaticamente quando programmazione impostazione del testo.
Ho trovato qualche problema quando si utilizza replaceCharactersInRange in delegate shouldChangeCharactersInRange.
Es: In stringa tastiera vietnamita "aa" -> "A", Quindi, se si utilizza il metodo replaceCharactersInRange allora i risultati non corretti
Si può provare in questo caso per caso UIControlEventEditingChanged:
[textField addTarget: azione di auto: @selector (textFieldDidChange :) forControlEvents: UIControlEventEditingChanged]
Ho avuto esattamente lo stesso problema. Ad esempio: Se il testo del campo di testo è "Ha" e replacementString è "f" e se utilizzo la funzione '- (BOOL) textField: (UITextField *) textField shouldChangeCharactersInRange: (NSRange) rangeString: (NSString *) stringa', il il risultato effettivo sarà "Haf" ma il risultato atteso dovrebbe essere "Hà" in vietnamita. –
seguito è quello che ho usato Swift 4
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let fieldText = textField.text else {
return false
}
// Append the existing textfield text with the new character
var text = fieldText + string
// If it is the very first character, textfield text will be empty so take the 'string' and on delete also textfield text get deleted with a delay
if range.location == 0{
text = string
}
return true
}
- 1. fare UITextField di funzionare come UISearchBar
- 2. Objective-C, Come posso ottenere il valore di un UITextField?
- 3. Un modo semplice per disabilitare un UITextField?
- 4. SearchBar textDidChange
- 5. Come selezionare un UITextField?
- 6. Assegnare un metodo per l'evento didEndOnExit di UITextField
- 7. Come posso rilevare un evento KeyPress in UITextField?
- 8. Qual è il modo migliore per ottenere la notifica delle modifiche alle selezioni UITextField?
- 9. Come posso creare un UITextField più arrotondato? Come il campo di ricerca in Safari su iPad
- 10. Metodo scanner per ottenere un carattere
- 11. Come ottenere un nome per il metodo di chiamata?
- 12. Come aggiungere UILongPressGestureRecognizer a un UITextField?
- 13. Come posso ottenere campi utilizzati in un metodo (.NET)?
- 14. Come posso spostare il pulsante di cancellazione in un UITextField?
- 15. Come posso rispondere agli eventi tattili su un UITextField?
- 16. Come ottenere un ID per un canale Netty?
- 17. Consenti solo caratteri alfanumerici per un UITextField
- 18. Come posso definire dinamicamente un metodo alias per un metodo di classe?
- 19. Come implementare un Observer per ottenere dati da un listener?
- 20. Testo segnaposto disallineato in UITextField di UISearchBar
- 21. Come posso cambiare il colore di un UITextField clearButton?
- 22. Come posso ottenere un keyIterator per una LinkedHashMap?
- 23. Come posso ottenere StackPanel per utilizzare un ItemTemplate?
- 24. Come posso ottenere un ID applicazione per la sandbox Paypal?
- 25. Come posso ottenere enum per contenere un trattino (-)?
- 26. Come posso dividere due numeri interi per ottenere un doppio?
- 27. Come posso ottenere un UIStackView per aggiornare il layout?
- 28. Come posso ottenere rapidamente emacs per aprire un nuovo buffer?
- 29. Come posso ottenere i bordi della città per un paese
- 30. Come posso mostrare un UIDatePicker invece di una tastiera quando un utente seleziona un UITextField?
Grazie! Ha funzionato magnificamente Ho dovuto fare quanto segue per ottenere la stringa completa: \t NSMutableString * textFieldString = [NSMutableString stringWithString: textField.text]; [textFieldString appendString: string]; – Jonah
Per tutti voi noobs come me là fuori. Questo è un metodo delegato che si rilascia come è. Vi darà il testo completo inserito più l'ultimo carattere digitato. Eccellente! –
Questo non è un buon approccio. Questo metodo si attiva prima che il testo cambi, quindi il testo che stai guardando non è ciò che l'utente ha appena digitato, e l'aggiunta di replaceString al testo esistente non è giusto perché l'utente potrebbe inserire il testo nel mezzo della stringa precedente , o sostituendolo del tutto (ecco perché c'è un parametro di intervallo). Salva te stesso un mal di testa e utilizzare la soluzione di Chris qui sotto invece. –