-3

I m using method:

textField:shouldChangeCharactersInRange:replacementString:

There are two UITextFields. First should not have characters limit second should have characters limit.

Please help how to do it.

Thanks in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
AKB
  • 132
  • 13
  • check this link - https://stackoverflow.com/questions/12304151/character-limit-for-multiple-uitextfields – Sunil Sharma Oct 09 '17 at 18:05
  • @SunilSharma The answer in the link is partially wrong. It doesn't handle lots of possible cases. – rmaddy Oct 09 '17 at 18:20
  • @rmaddy actually there are a lot of answer are available for this problem like https://stackoverflow.com/questions/5683376/textfielddidbeginediting-for-more-than-one-textfield and https://stackoverflow.com/questions/16865237/textfieldshouldreturn-for-multiple-textfields – Sunil Sharma Oct 09 '17 at 18:41

2 Answers2

1

Based on the following link Set the maximum character length of a UITextField

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField==secondTextField) {
    if(range.length + range.location > textField.text.length)
    {
        return NO;
    }

    NSUInteger newLength = [textField.text length] + [string length] - range.length;

    return newLength <= 10;
} else{
    return YES;
}
}
Lenin
  • 675
  • 6
  • 17
0

Declare second Textfield as property (var secondTextField). And check it in func

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == self.secondTextField{
        if range.location > yourLimit{
         return false
        }
    }
  • 1. The question is tagged Objective-C, not Swift. 2. This code doesn't compile. 3. It doesn't actually limit the amount of text properly. – rmaddy Oct 09 '17 at 18:17