Setting limits to TextBox and TextView in Xcode
I have created a Window based application with the Tab-bar as the RootViewController. On one of the tabs, I've provided a TextBox and TextView. I want to limit the number of characters that can be written inside them (i.e. TextBox and TextView). Please help if someon开发者_如何转开发e knows how to do it.. Thanks..
what do you mean by "tab bar" and "tab"? i assume you have a UITabBarController as RootViewController and a some subclass of UIView is one of the tabs that is shown when tapping on a TabBarItem. furthermore i assume your UITextView and (UITextField?) is added to that UIView subclass and NOT the TabBarItem?
if that's the case, you could do a check using the text property:
if([yourTextView.text length] > 42) {
// truncate text; e.g. throw away last part or first part until the length is below 42
}
should be the same for a UITextField - just use the text property again
You should implement the UITextFieldDelegate and/or UITextViewDelegate methods,
textField:shouldChangeCharactersInRange:replacementString:
or
textView:shouldChangeTextInRange:replacementText:
respectively.
Set an instance of the class that implements those methods as the delegate for your view. The logic in the method should examine the incoming text and decide what to do based on the length.
I've found another similar way to implement this problem using Delegates:
#define MAX_LENGTH 20
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.text.length >= MAX_LENGTH && range.length == 0)
{
return NO; // return NO to not change text
}
else
{return YES;}
}
精彩评论