在textField(_:shouldChangeCharactersInRange:replacementString :)中限制字符和字符长度 [英] Limiting characters and character length in textField(_:shouldChangeCharactersInRange:replacementString:)

查看:308
本文介绍了在textField(_:shouldChangeCharactersInRange:replacementString :)中限制字符和字符长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a username textField in my app that I want to limit to 24 characters and not allow "|" a pipe in the username.

我可以使用下面的代码分别完成每个操作,但是我很难将它们都合并到textField(_:shouldChangeCharactersInRange:replacementString :)中.

I am able to do each of these individually with the code below but I have having trouble combining these both into textField(_:shouldChangeCharactersInRange:replacementString:).

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

This code is successfully disallows a "|" in the username field.

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

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

This code successfully limits the username field to 24 characters.

  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
  }

我非常感谢您提供有关如何将它们都合并到textField(_:shouldChangeCharactersInRange:replacementString:)

I would really appreciate any advice on how to combine these both into textField(_:shouldChangeCharactersInRange:replacementString:)

推荐答案

尝试一下:

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
}

这篇关于在textField(_:shouldChangeCharactersInRange:replacementString :)中限制字符和字符长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆