【问题标题】:How do I limit text lengths for different UITextFields in Swift?如何限制 Swift 中不同 UITextField 的文本长度?
【发布时间】:2016-06-08 16:06:21
【问题描述】:

我正在处理一个iOS Xcode 7.3 Swift2 项目。它有不同的UITextFields,仅限于3 位数字,特别是数字。他们被分配到UITextFieldDelegate 并且运行良好。

这是我限制它们的地方:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
    let limitLength = 3
    if newLength > limitLength {
        return false
    }

    let numberOnly = NSCharacterSet.init(charactersInString: "0123456789")
    let stringFromTextField = NSCharacterSet.init(charactersInString: string)
    let strValid = numberOnly.isSupersetOfSet(stringFromTextField)

    return strValid
}

但是,一些UITextFields 仍然需要限制为数字并且也限制为单个 数字,我该如何在上面的部分中设置这个,仅适用于那些特定的UITextFields ?

UITextFields的名称需要是个位数:

widthInches
lengthInches

我尝试将它放在第一个后卫部分之后,但没有运气:

guard let text2 = widthInches.text else { return true }
let newLength2 = text2.characters.count + string.characters.count - range.length
let limitLength2 = 3
if newLength2 > limitLength2 {
    return false
}

【问题讨论】:

标签: ios swift2 uitextfield limit uitextfielddelegate


【解决方案1】:

你也可以试试这个限制文本字段的代码

实际上我在这里使用文本字段标签。因为自定义文本字段。 如果您在此条件标记中使用 TextfieldEffect 之类的自定义文本字段将帮助您限制文本字段。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
        
        if textField.tag == txtCountryCode.tag{
            let maxLength = 4
            let currentString: NSString = textField.text!
            let newString: NSString =
            currentString.stringByReplacingCharactersInRange(range, withString: string)
            return newString.length <= maxLength
        }

        
        if textField.tag == txtMobileNumber.tag{
            let maxLength = 10
            let currentString: NSString = textField.text!
            let newString: NSString =
            currentString.stringByReplacingCharactersInRange(range, withString: string)
            return newString.length <= maxLength
        }
        
        return true
    }

希望对你有帮助。

【讨论】:

  • 我不知道你可以将标签添加到 UITextFields,更不用说在 UITextFieldDelegate 中使用它们了。将来我将不得不对此进行研究。谢谢。
  • 实际上为什么我使用它是因为我没有使用 UITextfield 我正在使用自定义文本字段,这就是我遇到问题的原因,然后我使用 Tag 得到了解决方案。
【解决方案2】:

函数shouldChangeCharactersInRange 传入特定的文本字段作为其参数之一。您可以查看它,看看它是否指向与您要缩短的实例相同的实例,如下所示:

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

    guard let text = textField.text else { return true }
    var limitLength = 3
    if textField == widthInches || textField == lengthInches {
      limitLength = 1
    }

    let newLength = text.characters.count + string.characters.count - range.length
    if newLength > limitLength {
      return false
    }

    let numberOnly = NSCharacterSet.init(charactersInString: "0123456789")
    let stringFromTextField = NSCharacterSet.init(charactersInString: string)
    let strValid = numberOnly.isSupersetOfSet(stringFromTextField)

    return strValid
  }

假设所有其他要求都相同(仅数字),这就可以解决问题。

还有其他方法,例如 - 您可以子类化 UITextField 并添加一个 limitLength 字段,然后在委托中使用该字段,但这对于仅 2 个例外可能是矫枉过正。

【讨论】:

  • 谢谢。我不认为做一个子类是必要的。另一种方式非常有意义。
  • 我最终需要的 textFields 比我最初认为需要限制为 1 的要多。我同意你所说的,但不是 if..then 语句,而是用 case 语句多个 UITextFields。完美运行!
【解决方案3】:

您好,func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -&gt; Bool 中的 textField 参数是触发此事件的文本字段,因此您可以检查您的文本字段对象,如果等于其中一个对象,则执行不同的行为

希望对你有帮助

【讨论】:

    【解决方案4】:
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {  
        return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= TEXT_FIELD_LIMIT
    }
    

    这会根据 UTF-16 表示计算字符数,因为 range.length 以 UTF-16 为基数给出。如果需要用其他方式统计字符数,表达式可能会变长。如果您只想输入数字,请使用 textField.keyboardType = UIKeyboardTypeDecimalPad 。如果您想要特定的文本字段,则添加标签并比较它们,如果它们相等,您可以为此实现您的特定代码。

    查看此链接以获取详细答案: http://www.globalnerdy.com/2016/05/24/a-better-way-to-program-ios-text-fields-that-have-maximum-lengths-and-accept-or-reject-specific-characters/

    【讨论】:

    • 这与问题无关。
    • 我了解键盘类型,但是在 iPad 上它也有 $、& 等字符,这就是我指定要在我的代码中使用的实际数字的原因。 iPhone 没什么大不了的。
    【解决方案5】:

    为 swift 3 更新添加此类并将其命名为 TextField.swift。它将在情节提要上添加限制输入。

      import UIKit 
      private var maxLengths = [UITextField: Int]()
    
       extension UITextField {
    
     @IBInspectable var maxLength: Int {
      get {
         guard let length = maxLengths[self] else {
           return Int.max
       }
       return length
     }
      set {
        maxLengths[self] = newValue
        // Any text field with a set max length will call the limitLength
        // method any time it's edited (i.e. when the user adds, removes,
        // cuts, or pastes characters to/from the text field).
          addTarget(
              self,
              action: #selector(limitLength),
              for: UIControlEvents.editingChanged
          )
      }
     }
    
       func limitLength(textField: UITextField) {
         guard let prospectiveText = textField.text, 
          prospectiveText.characters.count > maxLength else {
         return
       }
    
          // If the change in the text field's contents will exceed its maximum 
         length,
         // allow only the first [maxLength] characters of the resulting text.
         let selection = selectedTextRange
    
        // text = prospectiveText.substring(with:Range<String.Index>
        (prospectiveText.startIndex ..< prospectiveText.index(after: maxLength))
        let s = prospectiveText
    
          // Get range 4 places from the start, and 6 from the end.
         let c = s.characters;
    
          let r = c.index(c.startIndex, offsetBy: 0)..<c.index(c.endIndex, offsetBy:   maxLength - c.count)
           text = s[r]
    
    
         // Access the string by the range.
    
    
         selectedTextRange = selection
        }
    
       }
    

    或在这里下载 - >TextField.swift

    【讨论】:

      猜你喜欢
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多