简体   繁体   English

如何在Swift中限制不同UITextField的文本长度?

[英]How do I limit text lengths for different UITextFields in Swift?

I have an iOS Xcode 7.3 Swift2 project I'm working on. 我有一个正在处理的iOS Xcode 7.3 Swift2项目。 It has different UITextFields that are limited to 3 digits, specifically only numbers. 它具有不同的UITextFields ,这些UITextFields仅限3个数字,尤其是数字。 They are assigned to the UITextFieldDelegate and it's working well. 它们被分配给UITextFieldDelegate ,并且运行良好。

Here is where I limit them: 这是我限制它们的地方:

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
}

However, some of the UITextFields need to be limited to numbers still AND also limited to a single digit, how can I institute this in the section above, only for those specific UITextFields ? 然而,一些的UITextFields需要局限于数字仍然还仅限于一个单一的数字,我怎么能在部分提起这上面,只对那些特定UITextFields

The names of the UITextFields that need to be single digits are: UITextFields的名称需要为UITextFields数字:

widthInches
lengthInches

I tried placing this after the first guard section with no luck: 我尝试将其放置在第一个警卫区之后,但没有运气:

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
}

You can also try this code for limit textfield 您也可以尝试使用此代码来限制文本字段

actually i am using here textfield tag. 实际上我在这里使用textfield标签。 Because custom textfield. 因为自定义文本字段。 If you using custom textfield like TextfieldEffect in this condition tag will help you for limit of Textfield. 如果在此条件标签中使用自定义文本字段(如TextfieldEffect) ,则将有助于您限制Textfield。

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
    }

I hope this will help you. 我希望这能帮到您。

The function shouldChangeCharactersInRange passes in the particular textField as one of its parameters. 函数shouldChangeCharactersInRange会将特定的textField作为其参数之一传递。 You can look at that and see if it points to the same instance as the ones you want to shorten, like this: 您可以查看它,并查看它是否指向与您要缩短的实例相同的实例,如下所示:

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
  }

Assuming all other requirements are the same (numbers only) this will do the trick. 假设所有其他要求都相同(仅数字),就可以解决问题。

There are other ways, for example - you could subclass UITextField and add a limitLength field, then use that field in the delegate, but that's probably overkill for just 2 exceptions. 例如,还有其他方法-您可以将UITextField子类化,并添加一个limitLength字段,然后在委托中使用该字段,但是对于2个异常而言,这可能会过高。

Hello in your func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool the textField param is the textField that has trigger this event so you can check with yours textfields objects and if are equal to one of them then make a different behavior 您好在您的func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool textField参数是触发此事件的textField,因此您可以检查您的textfields对象,如果它们等于其中之一然后做出不同的行为

I hope this helps you, 我希望这可以帮助你,

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
}

This counts the number of characters based on UTF-16 representation, as range.length is given in UTF-16 base. 这会根据UTF-16表示来计算字符数,因为range.length以UTF-16为基础给出。 If you need to count the number of characters in other ways, the expression may get longer. 如果您需要以其他方式计算字符数,则表达式可能会变长。 If you want only numbers to be input use textField.keyboardType = UIKeyboardTypeDecimalPad . 如果只想输入数字,请使用textField.keyboardType = UIKeyboardTypeDecimalPad If you want specific textFields then add tags and compare them and if they are equal you can implement your specific code for that. 如果要特定的textField,则添加标签并进行比较,如果它们相等,则可以为此实现特定的代码。

Check this link for detailed answer : 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/ 检查此链接以获取详细答案: http : //www.globalnerdy.com/2016/05/24/a-better-way-to-program-ios-text-fields-that-have-maximum-lengths-and-accept -或拒绝特定字符/

update for swift 3 add this class and call it TextField.swift. Swift 3的更新添加此类,并将其命名为TextField.swift。 it will add the limit input on the storyboard. 它将在情节提要板上添加限制输入。

  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
    }

   }

or download here - > TextField.swift 或在这里下载-> TextField.swift

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM