2015-01-04 21 views
23

Si tratta di un'estensione, non un duplicato, di How to check if a text field is empty or not in swiftControllare se il campo testo Swift contiene non-spazi

La data risposta,

@IBAction func Button(sender: AnyObject) { 
    if textField1.text != "" { 
     // textfield 1 
    } 
} 

non funziona per me, vale a dire, il se-loop viene attivato anche quando non viene inserito nulla nel campo di testo. (L'ho modificato dall'originale perché sto cercando di attivare il codice solo quando il campo contiene del testo).

La seconda risposta

@IBAction func Button(sender: AnyObject) { 
    if !textField1.text.isEmpty{ 

    } 
} 

arriva molto più vicino, ma accetta stringhe come " " non vuota. Potrei costruire qualcosa da solo, ma c'è una funzione che controllerà se una stringa contiene qualcosa di diverso da uno spazio bianco?

+0

Ecco la stessa domanda con le soluzioni in Objective-C: http://stackoverflow.com/questions/8238691/how-to- so-se-IO-has-blank-spazi a-UITextField-in-. Dovrebbe essere facile da tradurre in Swift. –

risposta

66

Si dovrebbe tagliare la stringa da caratteri di spaziatura e verificare se è vuota:

if !textField1.text.trimmingCharacters(in: .whitespaces).isEmpty { 
    // string contains non-whitespace characters 
} 

È inoltre possibile utilizzare CharacterSet.whitespacesAndNewlines per rimuovere caratteri di nuova riga pure.

+2

Potrei suggerire '! Str.stringByTrimmingCharactersInSet (whitespaceSet) .isEmpty'? I _think_ 'isEmpty' potrebbe essere un po 'più veloce dato che è O (N). – Ryan

+2

Direi che isEmpty è o almeno dovrebbe essere O (1) :) –

3
extension String { 
    var isEmptyField: Bool { 
     return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "" 
    } 
} 


if yourTextField.text.isEmptyField { 
    // Field is empty 
} else { 
    // Field is NOT empty 
} 
16

Di seguito è l'estensione ho scritto che funziona bene, soprattutto per coloro che provengono da un background di .NET:

extension String { 
    func isEmptyOrWhitespace() -> Bool { 

     if(self.isEmpty) { 
      return true 
     } 

     return (self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) == "") 
    } 
} 
3

akashivskyy answer in Swift 3.0:

let whitespaceSet = CharacterSet.whitespaces 
if !str.trimmingCharacters(in: whitespaceSet).isEmpty { 
    // string contains non-whitespace characters 
} 
1

risposta in Swift 3.0

if stringValue.trimmingCharacters(in: CharacterSet.whitespaces).isEmpty 
{} 
0

risposta in Swift 3. *, considera a capo, schede

extension String { 

    var containsNonWhitespace: Bool { 
     return !self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty 
    } 

} 
+0

Questa domanda ha già una risposta accettata, insieme a un'altra risposta in alto a votazione in Swift 3. – dfd

Problemi correlati