简体   繁体   English

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

[英]Limiting characters and character length in textField(_:shouldChangeCharactersInRange:replacementString:)

I have a username textField in my app that I want to limit to 24 characters and not allow "|"我的应用程序中有一个用户名 textField,我想将其限制为 24 个字符并且不允许使用“|” a pipe in the username.用户名中的管道。

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:).我可以使用下面的代码单独完成这些操作,但是我无法将它们组合到 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
    }
  }

This code successfully limits the username field to 24 characters.此代码成功地将用户名字段限制为 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
  }

I would really appreciate any advice on how to combine these both into textField(_:shouldChangeCharactersInRange:replacementString:)我非常感谢有关如何将它们组合到 textField(_:shouldChangeCharactersInRange:replacementString:) 中的任何建议

Try this:试试这个:

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
}

You can create your own custom text field as follow:您可以创建自己的自定义文本字段,如下所示:

import UIKit
@IBDesignable
class LimitedLengthField: UITextField {
    @IBInspectable
    var maxLength: Int = 10 { didSet { editingChanged(self) } }
    override func willMove(toSuperview newSuperview: UIView?) {
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
        editingChanged(self)
    }
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        editingChanged(self)
    }
    @objc func editingChanged(_ textField: UITextField) {
        textField.text = String(textField.text!.prefix(maxLength))
    }
}

Edit: If you would like to also exclude some characters you can add an ignored characters inspectable property to your field as follow:编辑:如果您还想排除某些字符,您可以向您的字段添加一个忽略字符的可检查属性,如下所示:

import UIKit
@IBDesignable class LimitedLengthField: UITextField {
    @IBInspectable var maxLength: Int = 24 {
        didSet { editingChanged(self) }
    }
    @IBInspectable var ignoredCharacters: String = "|" {
        didSet { editingChanged(self) }
    }
    override func willMove(toSuperview newSuperview: UIView?) {
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
        editingChanged(self)
    }
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        editingChanged(self)
    }
    @objc func editingChanged(_ textField: UITextField) {
        textField.text = String(text!.filter{!ignoredCharacters.contains($0) }.prefix(maxLength))
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 textField:shouldChangeCharactersInRange:replacementString:in subclass - textField:shouldChangeCharactersInRange:replacementString: in subclass 需要有关textField的帮助:shouldChangeCharactersInRange:replacementString: - Need assistance regarding textField:shouldChangeCharactersInRange:replacementString: 在UITextField中输入时不会调用textField:shouldChangeCharactersInRange:replacementString: - textField:shouldChangeCharactersInRange:replacementString: isn't called when inputing in a UITextField iOS 11中的密码自动填充会忽略从textField:shouldChangeCharactersInRange:replacementString返回的NO: - Password AutoFill in iOS 11 ignores NO returned from textField:shouldChangeCharactersInRange:replacementString: 当textfield:shouldChangeCharactersInRange:replacementString:在iPad iOS 9上返回NO时,它将崩溃 - when textfield:shouldChangeCharactersInRange:replacementString: return NO on iPad iOS 9, it will crash 使用rangeOfString和textfield shouldChangeCharactersInRange-删除字符? - using rangeOfString and textfield shouldChangeCharactersInRange - the delete character? 在文本字段中限制字符的问题 - Issue with limiting characters in textfield 使用`textField:shouldChangeCharactersInRange:`,我如何发现字符不匹配? - Using `textField:shouldChangeCharactersInRange:`, how do i found that characters are mismatch? Textfield应该迅速改变字符范围 - Textfield shouldchangecharactersinrange swift 文本字段shouldChangeCharactersInRange不被调用 - textfield shouldChangeCharactersInRange not called
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM