HI, I'm brand new to iPhone SDK and Objective-C and I can't work out how to limit the number of characters in a UITextField. When I searched it on the internet I found a few answers but they all said to put some code in the UITextFields delegate, but I don't have a UITextField delegate. And then I wondered how do you implement it (i.e. in Interface Builder cntrl-drag to delegate function). Thank you.
HI, I'm brand new to iPhone SDK and Objective-C and I can't work out how to limit the number of characters in a UITextField. When I searched it on the internet I found a few answers but they all said to put some code in the UITextFields delegate, but I don't have a UITextField delegate. And then I wondered how do you implement it (i.e. in Interface Builder cntrl-drag to delegate function). Thank you.
you can use like this functionality
on click
if(textfield.length == 4)
{
code
}
else
{
Alert
}
Elaborating a bit on the above, here's a piece of code that'll limit the length for you Alex, as well as stopping you entering %, & and ". Define kmaxCharacters in the header...
Code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >= kmaxCharacters && range.length == 0)
{
return NO; // return NO to not change text
}else{
if ([string isEqualToString:@"\""] || [string isEqualToString:@"-"] || [string isEqualToString:@"%"] ) {
return NO;
}
return YES;
}
}
Elaborating a bit on the above, here's a piece of code that'll limit the length for you Alex, as well as stopping you entering %, & and ". Define kmaxCharacters in the header...
Code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >= kmaxCharacters && range.length == 0)
{
return NO; // return NO to not change text
}else{
if ([string isEqualToString:@"\""] || [string isEqualToString:@"-"] || [string isEqualToString:@"%"] ) {
return NO;
}
return YES;
}
}
Thank you for that, I tried to put it in but I don't know which file it goes in and/or if I have to do any linking between the UITextField and the code.