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

时间:2016-05-21 18:31:05

标签: 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
    }
  }

此代码成功将用户名字段限制为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
  }

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

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:2)

您可以创建自己的自定义文本字段,如下所示:

import UIKit

@IBDesignable class LimitedLengthField: UITextField {
    @IBInspectable var maxLength: Int = 24    // set a default value
    override func awakeFromNib() {
        super.awakeFromNib()
        addTarget(self, action: #selector(editingChanged), forControlEvents: .EditingChanged)
    }
    func editingChanged(sender: UITextField) {
        guard let text = sender.text?.characters.prefix(maxLength) else { return }
        sender.text = String(text)
    }
}

enter image description here enter image description here

Sample project

编辑:如果您还要排除某些字符,可以在字段中添加忽略的字符可检查属性,如下所示:

@IBDesignable class LimitedLengthField: UITextField {
    @IBInspectable var maxLength: Int = 24
    @IBInspectable var ignoredCharacters: String = "|"
    var stringValue: String { return text ?? "" }
    var filteredText: String { return stringValue.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ignoredCharacters)).joinWithSeparator("") }
    override func awakeFromNib() {
        super.awakeFromNib()
        addTarget(self, action: #selector(editingChanged), forControlEvents: .EditingChanged)
    }
    func editingChanged(sender:UITextField) {
        sender.text = String(filteredText.characters.prefix(maxLength))
    }
}