【问题标题】:Swift 3 - Limit TextField to alphanumeric (with whitespace and hypens)Swift 3 - 将文本字段限制为字母数字(带有空格和连字符)
【发布时间】:2017-05-23 00:21:59
【问题描述】:

希望将文本字段输入限制为仅 A-Z、a-z、0-9、" " 和 -。目前有:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        if self.isNumericTextInput{
            let allowedCharacters = CharacterSet.decimalDigits
            let characterSet = CharacterSet(charactersIn: string)
            if allowedCharacters.isSuperset(of: characterSet) && returnFlag{
                return true
            } else{
                return false
            }

        } else{
            // Allow only alphanumerics, whitespace and hyphens
        }
        return
    }

【问题讨论】:

  • 您在哪里尝试将文本字段限制为字母、数字和那几个标点字符?您已经知道如何过滤数字。除了字符集之外,另一个是相同的。

标签: swift input whitespace textfield alphanumeric


【解决方案1】:

虽然回答晚了,但可能对某人有用。

斯威夫特 3:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    /// 1. replacementString is NOT empty means we are entering text or pasting text: perform the logic
    /// 2. replacementString is empty means we are deleting text: return true
    if string.characters.count > 0 {
        var allowedCharacters = CharacterSet.alphanumerics
        allowedCharacters.insert(charactersIn: " -") // "white space & hyphen" 

       let unwantedStr = string.trimmingCharacters(in: allowedCharacters)
       return unwantedStr.characters.count == 0
    }

    return true
}

注意:这也适用于将字符串粘贴到文本字段中。如果粘贴的字符串包含任何不需要的字符,将不会在文本字段中显示。

【讨论】:

    【解决方案2】:

    试试这个:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let characterSet = CharacterSet(charactersIn: string)
    
        let allowedCharacters = (self.isNumericTextInput
            ? CharacterSet.decimalDigits
            : CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 -"))
    
        return allowedCharacters.isSuperset(of: characterSet) && returnFlag
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 2013-07-07
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多