Подтвердить что ты не робот

Как проверить, пусто ли текстовое поле или нет в быстрой

Я работаю над кодом ниже, чтобы проверить текстовые поля textField1 и textField2, есть ли в них какой-либо ввод или нет.

Оператор IF ничего не делает, когда я нажимаю кнопку.

 @IBOutlet var textField1 : UITextField = UITextField()
 @IBOutlet var textField2 : UITextField = UITextField()
 @IBAction func Button(sender : AnyObject) 
  {

    if textField1 == "" || textField2 == "" 
      {

  //then do something

      }  
  }
4b9b3361

Ответ 1

Просто сравнение объекта текстового поля с пустой строкой "" - неправильный способ обойти это. Вы должны сравнить свойство textfield text, так как оно является совместимым типом и содержит информацию, которую вы ищете.

@IBAction func Button(sender: AnyObject) {
    if textField1.text == "" || textField2.text == "" {
        // either textfield 1 or 2 text is empty
    }
}

Swift 2.0:

Guard

guard let text = descriptionLabel.text where !text.isEmpty else {
    return
}
text.characters.count  //do something if it not empty

, если

if let text = descriptionLabel.text where !text.isEmpty
{
    //do something if it not empty  
    text.characters.count  
}

Swift 3.0:

Guard

guard let text = descriptionLabel.text, !text.isEmpty else {
    return
}
text.characters.count  //do something if it not empty

, если

if let text = descriptionLabel.text, !text.isEmpty
{
    //do something if it not empty  
    text.characters.count  
}

Ответ 2

Лучшее и красивое использование

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

    }
}

Ответ 3

другой способ проверки в реальном времени textField:

 @IBOutlet var textField1 : UITextField = UITextField()

 override func viewDidLoad() 
 {
    ....
    self.textField1.addTarget(self, action: Selector("yourNameFunction:"), forControlEvents: UIControlEvents.EditingChanged)
 }

 func yourNameFunction(sender: UITextField) {

    if sender.text.isEmpty {
      // textfield is empty
    } else {
      // text field is not empty
    }
  }

Ответ 4

, если пусть... где... {

Swift 3:

if let _text = theTextField.text, _text.isEmpty {
    // _text is not empty here
}

Swift 2:

if let theText = theTextField.text where !theTextField.text!.isEmpty {
    // theText is not empty here
}

guard... где... else {

Вы также можете использовать ключевое слово guard:

Swift 3:

guard let theText = theTextField.text where theText.isEmpty else {
    // theText is empty
    return // or throw
}

// you can use theText outside the guard scope !
print("user wrote \(theText)")

Swift 2:

guard let theText = theTextField.text where !theTextField.text!.isEmpty else {
    // the text is empty
    return
}

// you can use theText outside the guard scope !
print("user wrote \(theText)")

Это особенно полезно для цепей проверки, например, в формах. Вы можете написать guard let для каждой проверки и возврата или выбросить исключение, если есть критическая ошибка.

Ответ 5

Компактный маленький драгоценный камень для Swift 2/Xcode 7

@IBAction func SubmitAgeButton(sender: AnyObject) {

    let newAge = String(inputField.text!)        

if ((textField.text?.isEmpty) != false) {
        label.text = "Enter a number!"
    }
    else {
        label.text = "Oh, you're \(newAge)"

        return
    }

    }

Ответ 6

Может быть, я слишком поздно, но не можем ли мы проверить это:

   @IBAction func Button(sender: AnyObject) {
       if textField1.text.utf16Count == 0 || textField2.text.utf16Count == 0 {

       }
    }

Ответ 7

Хорошо, это может быть поздно, но в Xcode 8 у меня есть решение:

if(textbox.stringValue.isEmpty) {
    // some code
} else {
    //some code
}

Ответ 8

Как и в случае с быстрым 3/xcode 8, свойство text необязательно, вы можете сделать это следующим образом:

if ((textField.text ?? "").isEmpty) {
    // is empty
}

или

if (textField.text?.isEmpty ?? true) {
    // is empty
}

В качестве альтернативы вы можете сделать extenstion, например, ниже, и использовать его вместо:

extension UITextField {
    var isEmpty: Bool {
        return text?.isEmpty ?? true
    }
}

...

if (textField.isEmpty) {
    // is empty
}

Ответ 9

Я просто попытался показать вам решение в простом коде

@IBAction func Button(sender : AnyObject) {
 if textField1.text != "" {
   // either textfield 1 is not empty then do this task
 }else{
   //show error here that textfield1 is empty
 }
}

Ответ 10

Слишком поздно, и его работоспособность в Xcode 7.3.1

if _txtfield1.text!.isEmpty || _txtfield2.text!.isEmpty {
        //is empty
    }

Ответ 11

Я использовал UIKeyInput встроенную функцию hasText: docs

Для Swift 2.3 мне пришлось использовать его как метод вместо свойства (как это указано в документах):

if textField1.hasText() && textField2.hasText() {
    // both textfields have some text
}

Ответ 12

Простой способ проверки

if TextField.stringValue.isEmpty {

}