【问题标题】:How to prevent empty or whitespaces in UITextField in Swift?如何在 Swift 中防止 UITextField 中出现空白或空格?
【发布时间】:2016-05-09 15:36:16
【问题描述】:

我试图阻止 UITextField 输入空格字符或不输入字符,但仅适用于不输入字符。我需要的是:不允许用户在不输入任何字符和空格的情况下保存文本字段;但用户可以输入,例如:“新类别”。所以空格只允许在字母或数字之间,而不仅仅是空格。

这是我的代码:

@IBAction func btnAddCategory(sender: AnyObject) {
    let alert = UIAlertController(title: "Ajouter une catégorie", message: nil, preferredStyle: .Alert)
    alert.view.tintColor = Utils.colorFromHex(0x585858)
    let confirmAction = UIAlertAction(title: "OK", style: .Default, handler: ({ (_) in
        if let field = alert.textFields?[0] {
            if field.text! == NSCharacterSet.whitespaceCharacterSet() || field.text! == ""{
                self.displayAlert("Attention", alertMsg: "Vous ne pouvez pas créer des données vides")
            } else {
                if self.checkDuplicates(field.text!) {
                    self.displayAlert("Attetion", alertMsg: "Vous avez déjà une catégorie avec ce nom !")
                } else {
                    self.saveCategory(field.text!)
                    self.tableView.reloadData()
                }
            }
        }
        }
    ))

    let cancelAction = UIAlertAction(title: "Annuler", style: .Cancel, handler: nil)

    alert.addTextFieldWithConfigurationHandler({(textField) in
        textField.placeholder = "Titre"
        textField.font = UIFont(name: "Roboto-Light", size: 15)!
    })

    alert.addAction(confirmAction)
    alert.addAction(cancelAction)

    self.presentViewController(alert, animated: true, completion: nil)
}

那么有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: swift uitextfield ios9


    【解决方案1】:

    如果你想在数字字符时防止空格,你可以实现 UITexfieldDelegate 协议的 textfield(textfield:UITextField, shouldChangeCharactersInRange: NSRange, replacementString: String) -> Bool 委托方法。
    在实现中,如果新字符是空格,则应返回 false,否则应返回 true
    我们在这里所做的是创建一组字符进行检查。
    NSCharacterSet 已经提供了不同的字符集。

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
            let inValidCharacterSet = NSCharacterSet.whitespaceCharacterSet()
            guard let firstChar = string.unicodeScalars.first else {return true}
            return !inValidCharacterSet.isCharInSet(Character(firstChar))
        }
    

    isCharInSetNSCharacterSet 的扩展(我从 S.O. 的某处采用并修改了该方法):

    extension NSCharacterSet {
        func isCharInSet(char: Character) -> Bool {
            var found = true
            for ch in String(char).utf16 {
                if !characterIsMember(ch) { found = false }
            }
            return found
        }
    }
    

    【讨论】:

    • 我需要的是:不允许用户在不输入任何字符且只输入空格的情况下保存文本字段;但用户可以输入,例如:“新类别”。所以空格只允许在字母或数字之间,而不仅仅是空格。
    • @Marco Almeida,你应该在原来的问题中这么说。
    • @paulvs 我的错,对不起。我编辑了这个问题。但是你有什么建议吗?
    • 您可以使用StringhasPrefixhasSuffix方法来检查UITextFieldtext字符串是否以字符串开头或结尾。
    • 哎呀,误读了你的问题,这不是吗:textField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).characters.count == 0
    【解决方案2】:

    Swift 5.1、Xcode 11

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard range.location == 0 else {
            return true
        }
    
        let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string) as NSString
        return newString.rangeOfCharacter(from: CharacterSet.whitespacesAndNewlines).location != 0
    }
    

    【讨论】:

    • 没有关于如何使用它的指导。不是很有帮助。
    • 是的,但没有解释它是什么以及它是如何工作的。
    • 另外,如果你输入任何字符,现在你不能退格了。
    • 这段代码只会阻止第一个字符成为空格,一旦你开始输入,你可以做任何你想做的事情,包括无尽的空格
    【解决方案3】:

    终于用这段代码修复了它:

    @IBAction func btnAddCategory(sender: AnyObject) {
        let alert = UIAlertController(title: "Ajouter une catégorie", message: nil, preferredStyle: .Alert)
        alert.view.tintColor = Utils.colorFromHex(0x585858)
        let confirmAction = UIAlertAction(title: "OK", style: .Default, handler: ({ (_) in
            if let field = alert.textFields?[0] {
    
                let strLength = field.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).characters.count
    
                if  strLength == 0 {
                    self.displayAlert("Attention", alertMsg: "Vous ne pouvez pas créer des données vides")
                } else {
                    if self.checkDuplicates(field.text!) {
                        self.displayAlert("Attetion", alertMsg: "Vous avez déjà une catégorie avec ce nom !")
                    } else {
                        self.saveCategory(field.text!)
                        self.tableView.reloadData()
                    }
                }
            }
            }
        ))
    
        let cancelAction = UIAlertAction(title: "Annuler", style: .Cancel, handler: nil)
    
        alert.addTextFieldWithConfigurationHandler({(textField) in
            textField.placeholder = "Titre"
            textField.font = UIFont(name: "Roboto-Light", size: 15)!
        })
    
        alert.addAction(confirmAction)
        alert.addAction(cancelAction)
    
        self.presentViewController(alert, animated: true, completion: nil)
    }
    

    【讨论】:

      【解决方案4】:
          func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      
              let   trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)
              var subString = textField.text as NSString?
              subString = subString?.replacingCharacters(in: range, with: string) as NSString?
      
              if (textField.tag == 0 || textField.tag == 1)
              {
                  let acceptedInput = NSCharacterSet.alphanumerics.inverted
                  let filteredString = (trimmedString.components(separatedBy: acceptedInput)).joined(separator: "")
      
                  if trimmedString == filteredString
                  {
                      textField.text = (textField.text! as NSString).replacingCharacters(in: range, with: filteredString)
      
                      return false
                  }
                  else
                  {
                      return false
                  }
              }
              return true
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-23
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 2012-05-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多