user8411642
user8411642

Reputation:

Issue with limiting characters in textfield

This is how I am limiting the characters entered in two textFields...

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == textField1 {
            if (textField1.text?.characters.count)! + (string.characters.count - range.length) > 11 {

                return false
            }
            return true
        } else if textField == textField2 {
            if (textField2.text?.characters.count)! + (string.characters.count - range.length) > 15 {

                return false
            }

        }
         return true
    }

But the issue is only textField1 is not allowing to enter more than 11 characters but textField2 is accepting any number of characters while it should not have allowed to enter more than 15 characters.

Upvotes: 0

Views: 47

Answers (3)

SolinLiu
SolinLiu

Reputation: 209

Maybe you forgot to set textField2's delegate,And I did a test,your code is work!

Upvotes: 0

rptwsthi
rptwsthi

Reputation: 10172

Since there's nothing wrong with your code, you can try following check list:

  • Check if textfield 2 outlet is set. You can do it manually or
  • you can try adding a breakpoint (or print) in you else if textField == textField2 {} block
  • Also check if delegate of textField2 is set to self as well

If control comes to else if block then your code must work.

Upvotes: 1

Bishan
Bishan

Reputation: 401

I think you haven't set the delegate in viewDidLoad,

import UIKit

class ViewController: UIViewController, UITextFieldDelegate{

    @IBOutlet var textField1 :UITextField!
    @IBOutlet var textField2 :UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        self.textField1.delegate = self
        self.textField2.delegate = self


    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == textField1 {
            if (textField1.text?.characters.count)! + (string.characters.count - range.length) > 11 {

                return false
            }
            return true
        } else if textField == textField2 {
            if (textField2.text?.characters.count)! + (string.characters.count - range.length) > 11 {

                return false
            }

        }
        return true
    }

Upvotes: 0

Related Questions