限制textField中的字符和字符长度(_:shouldChangeCharactersInRange:replacementString :)

chi*_*arm 0 ios swift

我的应用程序中有一个用户名textField,我想限制为24个字符,不允许"|" 用户名中的管道.

我可以使用下面的代码单独执行这些操作,但是我无法将这两者组合到textField(_:shouldChangeCharactersInRange:replacementString :)中.

此代码成功禁止"|" 在用户名字段中.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if textField === usernameField {
      // Create an `NSCharacterSet` set
      let set = NSCharacterSet(charactersInString:"|")

      // At every character in this "set" contained in the string,
      // split the string up into components which exclude the characters
      // in this inverse set
      let components = string.componentsSeparatedByCharactersInSet(set)

      // Rejoin these components
      let filtered = components.joinWithSeparator("")

      // If the original string is equal to the filtered string, i.e. if no
      // characters were present to be eliminated, the input is valid
      // and the statement returns true; else it returns false
      return string == filtered
    } else {
      return true
    }
  }
Run Code Online (Sandbox Code Playgroud)

此代码成功将用户名字段限制为24个字符.

  func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // Added to limit title to <= 40 characters
    guard let text = meetupTitleTextField.text else { return true }

    let newLength = text.utf16.count + string.utf16.count - range.length
    return newLength <= 48 // Bool
  }
Run Code Online (Sandbox Code Playgroud)

我真的很感激如何将这两者结合到textField(_:shouldChangeCharactersInRange:replacementString :)中的任何建议

Cod*_*ent 5

试试这个:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == usernameField, let text = textField.text {
        let newLength = text.characters.count + string.characters.count - range.length
        return newLength <= 48 && !string.containsString("|")
    }

    return true
}
Run Code Online (Sandbox Code Playgroud)