ios 如果我使用自己设计的键盘,如何限制Swift,UITextField中的字符数?

6tr1vspr  于 2023-01-06  发布在  iOS
关注(0)|答案(2)|浏览(129)

实际上我试着用这个

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let textFieldText = textField.text,
        let rangeOfTextToReplace = Range(range, in: textFieldText) else {
            return false
    }
    let substringToReplace = textFieldText[rangeOfTextToReplace]
    let count = textFieldText.count - substringToReplace.count + string.count
    return count <= 10
}

但是只有当我在我的电脑上打字时它才能工作。但是如果我用我设计的键盘打字,它就不能工作了。顺便说一下,我设计的键盘如下。

@IBAction func digits(_ sender: UIButton) {
        
      textField.text! += String(sender.tag)
        
  }

在这种情况下,是否有功能限制字符数?

oxcyiej7

oxcyiej71#

使用UITextField扩展将textField的字符数固定为:-

private var kAssociationKeyMaxLength: Int = 0

extension UITextField {

@IBInspectable var maxLength: Int {
    get {
        if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
            return length
        } else {
            return Int.max
        }
    }
    set {
        objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
        self.addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
    }
}

func isInputMethod() -> Bool {
    if let positionRange = self.markedTextRange {
        if let _ = self.position(from: positionRange.start, offset: 0) {
            return true
        }
    }
    return false
}

@objc func checkMaxLength(textField: UITextField) {
    
    guard !self.isInputMethod(), let prospectiveText = self.text,
        prospectiveText.count > maxLength
        else {
            return
    }
    
    let selection = selectedTextRange
    let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
    text = prospectiveText.substring(to: maxCharIndex)
    selectedTextRange = selection
  }

}

代码中的用法如下:-

self.textField.maxLength = 8

此外,您还可以通过选择文本字段、检入属性检查器从情节提要修复它,如下图所示:-

af7jpaap

af7jpaap2#

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
 guard let text = textField.text else { return true }
 let newLength = text.count + string.count - range.length
 return newLength <= 10

}

相关问题