2012-06-22 11 views
24

nessuno può aiutarmi con questo: ho bisogno di implementare UITextField per il numero di input. Questo numero dovrebbe sempre essere in formato decimale con 4 posti, ad es. 12.3456 o 12.3400. Così ho creato NSNumberFormatter che mi aiuta con i decimali.come spostare il cursore in UITextField dopo aver impostato il suo valore

sto impostando il valore UITextField nel metodo

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string . L'input di input, utilizzo di formattatore e infine chiamata [textField setText: myFormattedValue];

Funziona bene ma questa chiamata sposta anche il cursore alla fine del campo. Questo è indesiderato. Per esempio. Ho 12.3400 nel mio campo e il cursore si trova all'inizio e il tipo di utente numero 1. Il valore del risultato è 112,3400 ma il cursore viene spostato alla fine. Voglio terminare con il cursore quando l'utente si aspetta (subito dopo il numero 1 aggiunto di recente). Ci sono alcuni argomenti su come impostare il cursore in TextView ma questo è UITextField. Ho anche provato a catturare selectedTextRange del campo, che salva correttamente la posizione del cursore, ma dopo la chiamata al metodo setText, questo cambia automaticamente e l'origine UITextRange viene persa (modificata in corrente). spero che la mia spiegazione sia chiara.

Per favore, aiutami con questo. Grazie mille.

EDIT: Infine, ho deciso di passare la funzionalità a modificare il formato dopo l'intero montaggio e funziona abbastanza bene. L'ho fatto aggiungendo un selettore forControlEvents:UIControlEventEditingDidEnd.

+0

Quando si legge il 'selectedTextRange', si fa a non copiarla come una proprietà nella classe che funge da' UITextFieldDelegate' e poi ri-set dopo 'setText:'? –

+1

Phillip, che non funziona.Dopo aver impostato il testo con setText, il UITextRange che hai raccolto prima di impostare il testo viene reimpostato su null e quindi non puoi riapplicarlo successivamente al UITextField finito. – JasonD

risposta

2

implementare il codice descritto in questa risposta: Moving the cursor to the beginning of UITextField

NSRange beginningRange = NSMakeRange(0, 0); 
NSRange currentRange = [textField selectedRange]; 
if(!NSEqualRanges(beginningRange, currentRange)) 
{ 
    [textField setSelectedRange:beginningRange]; 
} 

EDIT: Da this answer, sembra che si può semplicemente utilizzare questo codice con il tuo UITextField se si sta utilizzando iOS 5 o superiore. Altrimenti, è necessario utilizzare invece UITextView.

38

Dopo la modifica della proprietà UITextField.text, qualsiasi riferimento precedente a UITextPosition o UITextRange oggetti associati al vecchio testo verrà impostato su zero dopo aver impostato la proprietà di testo. È necessario memorizzare quale sarà l'offset del testo dopo la manipolazione PRIMA di impostare la proprietà del testo.

questo ha funzionato per me (si noti, si ha a verificare se cursorOffset è < textField.text.length se si rimuove tutti i caratteri dalla t nell'esempio seguente):

- (BOOL) textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange) range replacementString:(NSString *) string 

{ 
    UITextPosition *beginning = textField.beginningOfDocument; 
    UITextPosition *start = [textField positionFromPosition:beginning offset:range.location]; 
    UITextPosition *end = [textField positionFromPosition:start offset:range.length]; 
    UITextRange *textRange = [textField textRangeFromPosition:start toPosition:end]; 

    // this will be the new cursor location after insert/paste/typing 
    NSInteger cursorOffset = [textField offsetFromPosition:beginning toPosition:start] + string.length; 

    // now apply the text changes that were typed or pasted in to the text field 
    [textField replaceRange:textRange withText:string]; 

    // now go modify the text in interesting ways doing our post processing of what was typed... 
    NSMutableString *t = [textField.text mutableCopy]; 
    t = [t upperCaseString]; 
    // ... etc 

    // now update the text field and reposition the cursor afterwards 
    textField.text = t; 
    UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorOffset]; 
    UITextRange *newSelectedRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition]; 
    [textField setSelectedTextRange:newSelectedRange]; 

    return NO; 
} 
+2

ha funzionato benissimo per me. Grazie, JasonD! –

+2

Funziona perfettamente. Grazie!!! – RohinNZ

+0

tnx molto, ho aggiunto la versione rapida sotto per i pigri :) – ergunkocak

3

Ed ecco la rapida versione:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 
    let beginning = textField.beginningOfDocument 
    let start = textField.positionFromPosition(beginning, offset:range.location) 
    let end = textField.positionFromPosition(start!, offset:range.length) 
    let textRange = textField.textRangeFromPosition(start!, toPosition:end!) 
    let cursorOffset = textField.offsetFromPosition(beginning, toPosition:start!) + string.characters.count 

// just used same text, use whatever you want :) 
    textField.text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) 

    let newCursorPosition = textField.positionFromPosition(textField.beginningOfDocument, offset:cursorOffset) 
    let newSelectedRange = textField.textRangeFromPosition(newCursorPosition!, toPosition:newCursorPosition!) 
    textField.selectedTextRange = newSelectedRange 

    return false 
} 
2

Ecco un rapido 3 versione

extension UITextField { 
    func setCursor(position: Int) { 
     let position = self.position(from: beginningOfDocument, offset: position)! 
     selectedTextRange = textRange(from: position, to: position) 
    } 
} 
0

Che cosa realmente w orked per me era molto semplice, basta utilizzato spedizione asincrona principale:

DispatchQueue.main.async(execute: { 
    textField.selectedTextRange = textField.textRange(from: start, to: end) 
}) 
Problemi correlati