swift2 如何限制Swift中不同UITextFields的文本长度?

wlwcrazw  于 2022-11-06  发布在  Swift
关注(0)|答案(5)|浏览(267)

我有一个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
}
0yg35tkg

0yg35tkg1#

您也可以尝试将此代码用于限制文本字段

实际上我在这里使用了textfield标签。因为自定义textfield。如果你在这个条件下使用自定义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
    }

我希望这对你有帮助。

f87krz0w

f87krz0w2#

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

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字段,然后在委托中使用该字段,但仅对于两个异常,这可能有点过头了。

4nkexdtk

4nkexdtk3#

Hello在您的func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool中,textField参数是触发此事件的textField,因此您可以检查您的textfield对象,如果等于其中一个对象,则执行不同的行为
我希望这对你有帮助,

ehxuflar

ehxuflar4#

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。如果您需要特定的textFields,则添加标记并比较它们,如果它们相等,则可以为此实现您的特定代码。
请查看此链接以了解详细答案: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/

t5zmwmid

t5zmwmid5#

update for 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

相关问题