2016-02-25 29 views
5

Ho implementato alcune funzionalità TextField nella mia app, quindi ho usato i delegati di TextField ma mostra alcuni errori come "Il valore della stringa di tipo non ha lunghezza membro" I don " so come risolvere questo per favore aiutami a risolvere questo problema.Swift: il valore di tipo 'stringa' non ha 'lunghezza' membro

Qui do il codice di ciò che sto provando.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 
    var oldLength: Int = textField.text!.characters.count 
    var replacementLength: Int = string.characters.count 
    var rangeLength: Int = range.length 
    var newLength: Int = oldLength - rangeLength + replacementLength 
    if textField.tag == 1 { 
     if string.length > 0 && !NSScanner.scannerWithString(string).scanInt(nil) { **------>//Error was showed in this line.** 
      return false 
     } 
     // This 'tabs' to next field when entering digits 
     if newLength == 5 { 
      if textField == txtOtp4 { 
       textField.resignFirstResponder() 
      } 
     } 
     else if oldLength > 0 && newLength == 0 { 

     } 

     return newLength <= 4 
    } 
    else { 
     if newLength == 11 { 
      if textField == txtPhoneNumber { 
       textField.resignFirstResponder() 
      } 
      return newLength <= 10 
     } 
    } 
    return true 
    // This allows numeric text only, but also backspace for deletes 
} 
+2

perché stai usando 'string.length' in una riga ma' string.characters.count' nell'altra? – luk2302

risposta

13

Sostituire

if string.length > 0 

da

if string.characters.count > 0 
+0

Grazie per la tua risposta @Tim Vermeulen. –

+0

Funziona ma mostra nuovi problemi. –

+0

Quali sono gli errori? –

8

Se stai usando Swift 2.0, è necessario utilizzare

string.characters.count 

per ottenere il numero di caratteri della stringa .

+0

Grazie a @mohonish –

Problemi correlati