Reputation:
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
Reputation: 209
Maybe you forgot to set textField2's delegate,And I did a test,your code is work!
Upvotes: 0
Reputation: 10172
Since there's nothing wrong with your code, you can try following check list:
breakpoint
(or print) in you else if textField == textField2 {}
blockdelegate
of textField2
is set to self
as wellIf control comes to else if
block then your code must work.
Upvotes: 1
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