-4

How can limit the characters of UITextField without using delegate methods. Im using UITableView in which i have UITextField in cell and used in different position within same screen and i want to limit text field on certain position UITableViewCell. Any help will be appreciated.

MRizwan33
  • 2,723
  • 6
  • 31
  • 42

2 Answers2

2

I faced same problem some time ago. However not using delegates is not correct way. you should use delegate and control the behaviour depending upon the position.

  1. Make a function in your tableViewCell class, Let's say that's

    -(void)setMyCellTag:(NSInteger)tag
    {
        self.tag = tag;
    }
    
  2. Now call this method from your cellForRowAtIndexPath function as,

    [cell setMyCellTag:indexPath.row];
    
  3. Use condition in UITextField delegate method that,

    if(self.tag == yourposition)
    {
       //Do Something
    }
    

Simple. Thanks for reading.

Najam
  • 1,129
  • 11
  • 32
1
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    let currentCharacterCount = textField.text?.characters.count ?? 0
    if (range.length + range.location > currentCharacterCount){
        return false
    }
    let newLength = currentCharacterCount + string.characters.count - range.length
    return newLength <= 1 // set your limit
}

make sure textfield delegate

Akshay Degada
  • 139
  • 2
  • 13