0

I have created a protocol with extension and set the the textfield method properly but when I created the custom class , I fetched the value but not able to send back to the protocol.

protocol Limiter {
    var  limit : Int {get set}
}
extension UIViewController: UITextFieldDelegate{

    public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let tf = textField.text ?? ""
        guard let stringRange = Range(range, in: tf) else { return false }

              // add their new text to the existing text
              let updatedText = tf.replacingCharacters(in: stringRange, with: string)

              print(updatedText)
        return updatedText.count  <= (textField as! Limiter).limit
     }

}
//Custom class 
class TextFieldLimiter: UITextField , Limiter{
    var limit: Int = 0

 @IBInspectable var maxLength: Int {
   get {
    print(limit)
     return limit
   }
   set {
     limit = newValue
    print(limit)
   }
 }   
}

I tried this code and am not sure I'm doing correctly or not.

So, please help me out...

Thank you in advance

  • 1
    Check this: https://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield/29804183#29804183 – Andreas Oetjen Feb 07 '20 at 07:06
  • Yes , but when I tried that option it partly works for me... If I try to paste some big text then it allows me... I want to allow to paste only the text whose limit is less or equal to my maximum length .. Is this possible? –  Feb 07 '20 at 09:15

1 Answers1

0

There are multiple solutions to be found in the web, depending on your usage

The best would be to use the UITextFieldDelegate protocol, esp. textField(_:shouldChangeCharactersIn:replacementString:):

  • You could let your subclass TextFieldLimiter implement the delegate and handle the protocol method there.
    • But this only works if there are no other delegates set, because there can be only one.
  • You could implement the delegate on the view controller and check if the sender is a TextFieldLimiter and check the limits there
    • This would lead to repeated code
    • But you could delegate from there to a to-be-written validate function that you would implement in TextFieldLimiter

You could also try this in your subclass TextFieldLimiter without using the delegate, for example override override func canPerformAction and check if it's the paste action and then check if the paste buffer is too big or not to allow the action or not. But this is a litte more tricky, and you have to also consider the undo case.

Andreas Oetjen
  • 9,889
  • 1
  • 24
  • 34