【问题标题】:How to check if a text field is empty or not in swift如何快速检查文本字段是否为空
【发布时间】:2014-07-28 22:51:17
【问题描述】:

我正在编写下面的代码来检查textField1textField2 文本字段中是否有任何输入。

当我按下按钮时,IF 语句没有执行任何操作。

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

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

  //then do something

      }  
  }

【问题讨论】:

    标签: swift textbox


    【解决方案1】:

    简单地将文本字段 object 与空字符串 "" 进行比较并不是解决此问题的正确方法。您必须比较文本字段的 text 属性,因为它是兼容类型并包含您要查找的信息。

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

    Swift 2.0:

    守卫

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

    如果

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

    Swift 3.0:

    守卫

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

    如果

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

    【讨论】:

    • 文本字段中有两个空格是什么意思?
    • 文本字段中的空格:if let text = descriptionLabel.text, !text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty {
    • Java 出身,学得很快,“守卫”看起来很凶
    • @chrisl08 为什么?在某些情况下它很棒(例如在验证链中,请查看本页中的第一个示例:thatthinginswift.com/guard-statement-swift
    【解决方案2】:

    更好更美观的使用

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

    【讨论】:

    • 在 Swift 2 中不再起作用,因为 text 属性是可选的。在下面检查我的答案。
    • text property 是可选的。在其后添加 !if textField1.text!.isEmpty || textField2.text!.isEmpty...
    • 请记住,如果该字段是必填项,用户可以输入一个空格,如果对您很重要,您应该检查此条件。
    【解决方案3】:

    也许我有点太晚了,但我们不能这样检查吗:

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

    【讨论】:

      【解决方案4】:

      我只是想用一个简单的代码向你展示解决方案

      @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
       }
      }
      

      【讨论】:

        【解决方案5】:

        另一种查看实时文本字段源的方法:

         @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
            }
          }
        

        【讨论】:

          【解决方案6】:

          适用于 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
              }
          
              }
          

          【讨论】:

            【解决方案7】:

            如果让...哪里... {

            Swift 3

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

            斯威夫特 2

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

            守卫...哪里...其他{

            您也可以使用关键字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)")
            

            斯威夫特 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,如果出现严重错误,则返回或抛出异常。

            【讨论】:

              【解决方案8】:

              简单的检查方法

              if TextField.stringValue.isEmpty {
              
              }
              

              【讨论】:

              • 注意,我们收到了关于这在 XCode 8 中不起作用的报告。
              【解决方案9】:

              为时已晚,它在 Xcode 7.3.1 中工作正常

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

              【讨论】:

                【解决方案10】:

                好的,这可能会迟到,但在 Xcode 8 中我有一个解决方案:

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

                【讨论】:

                • 你也可以试试 textField.text.isEmpty
                【解决方案11】:

                我使用了UIKeyInput的内置功能hasTextdocs

                对于 Swift 2.3,我不得不将它用作方法而不是属性(正如文档中所引用的那样):

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

                【讨论】:

                • 这已更改为 Swift 3 中的实例属性 .hasText
                • 问题是用户也可以添加简单的空格
                【解决方案12】:

                现在在 swift 3 / xcode 8 中,文本属性是可选的,你可以这样做:

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

                或:

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

                或者,您可以进行如下扩展并使用它来代替:

                extension UITextField {
                    var isEmpty: Bool {
                        return text?.isEmpty ?? true
                    }
                }
                
                ...
                
                if (textField.isEmpty) {
                    // is empty
                }
                

                【讨论】:

                • 鉴于 Swift 应该简化事情的想法,这似乎是苹果采取的不同途径。严重地。 ;)
                • text?.isEmpty ?? true 是错误的。它只会解开 text 属性,但永远不会调用结果 (true)。正确的语法是text?.isEmpty ?? falsetext?.isEmpty == true。我更喜欢后者,但在这种特殊情况下,文本永远不会返回 nil 你可以强制解开它return text!.isEmpty
                • 我会说text?.isEmpty ?? falsetext?.isEmpty == true 都不正确,因为在这两种情况下,您都假设文本不能为 nil,这是错误的假设(请参阅 Apple 在 UITextField 中的定义:open var text: String? // default is nil)所以 Apple 在这里实际上表明这可以为零。实际上,目前它不是零,但将来可能会改变,特别是如果 Apple 在他们的代码中添加这样的注释。因此,如果 text 为 nil,则应将其视为 textfield 为空。使用 hasText 属性很好,但它仅适用于 iOS 10.0+
                【解决方案13】:

                Swift 4.x 解决方案


                @IBOutlet var yourTextField: UITextField!
                
                 override func viewDidLoad() {
                     ....
                     yourTextField.addTarget(self, action: #selector(actionTextFieldIsEditingChanged), for: UIControlEvents.editingChanged)
                  }
                
                 @objc func actionTextFieldIsEditingChanged(sender: UITextField) {
                     if sender.text.isEmpty {
                       // textfield is empty
                     } else {
                       // text field is not empty
                     }
                  }
                

                【讨论】:

                • 这如何回答这个问题?
                • @rollstuhlfahrer,谢谢!当我第一次给出答案时,我已经给出了最新 Swift 版本的答案。感谢您指出。希望这个答案有帮助。
                【解决方案14】:

                Swift 4/xcode 9

                IBAction func button(_ sender: UIButton) {
                        if (textField1.text?.isEmpty)! || (textfield2.text?.isEmpty)!{
                                ..............
                        }
                }
                

                【讨论】:

                  【解决方案15】:

                  斯威夫特 4.2

                  您可以为每个文本字段使用通用函数,只需在基本控制器中添加以下函数

                  // White space validation.
                  func checkTextFieldIsNotEmpty(text:String) -> Bool
                  {
                      if (text.trimmingCharacters(in: .whitespaces).isEmpty)
                      {
                          return false
                  
                      }else{
                          return true
                      }
                  }
                  

                  【讨论】:

                  • 单行代码:return (text.trimmingCharacters(in: .whitespaces).isEmpty) ? false : true
                  【解决方案16】:

                  使用这个扩展

                  extension String {
                      func isBlankOrEmpty() -> Bool {
                  
                        // Check empty string
                        if self.isEmpty {
                            return true
                        }
                        // Trim and check empty string
                        return (self.trimmingCharacters(in: .whitespaces) == "")
                     }
                  }
                  

                  像这样

                  // Disable the Save button if the text field is empty.
                  let text = nameTextField.text ?? ""
                  saveButton.isEnabled = !text.isBlankOrEmpty()
                  

                  【讨论】:

                  • 为什么不直接返回trimmingCharacters(in: .whitespaces).isEmpty
                  猜你喜欢
                  • 2015-12-28
                  • 1970-01-01
                  • 2010-10-19
                  • 2016-11-04
                  • 2012-12-29
                  • 2021-07-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2014-02-01
                  相关资源
                  最近更新 更多