如何为textField

时间:2015-11-18 11:44:20

标签: ios objective-c uitextfield objective-c-category

我想创建与

相同的类别
 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
 replacementString:(NSString *)string

此方法的优点是不允许用户输入无效字符。

是否可以在TextFiled类别中管理此方法。

以下代码验证了文本字段,任何人都可以帮助我创建它的类别。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

 if (textField == NameText )
    {
        if ([string isEqualToString:@""])
        {
            NSString *originalString = textField.text;
            NSInteger newLength = [textField.text length];
            if (originalString.length > newLength)
                NameText.text = [originalString substringToIndex:newLength];
            return YES;
        }
        else
        {
            BOOL canEdit=NO;

            NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"1234567890-/:;()&@\".,?!'[]{}#%^*+=_\\|~<>$£₹€•"];
            for (int i = 0; i < [string length]; i++)
            {
                unichar c = [string characterAtIndex:i];
                if ([myCharSet characterIsMember:c])
                {
                    canEdit=NO;
                }
                else
                {
                    if ([NameText.text length] >= 10)
                    {
                        canEdit=NO;
                    }
                    else
                    {
                        canEdit=YES;
                    }
                }
            }
            return canEdit;
        }
    }
 return YES;
}
  

注意:我不想创建任何显示警报的自定义方法   当用户输入无效数据时。我希望该用户无法进入   数据无效。

1 个答案:

答案 0 :(得分:0)

@interface myLimitedTextView: UITextView <UITextViewDelegate>

@end

@implementation 

-(instancetype) init {  // not sure from the top of my head if there are more init variancies to be overwritten. 

  self = [super init];
  if (self) {
     self.delegate = self; //Do not set a delegate in IB!
  }
}

// overwriting getters and setters may even be more efficient 

- (void) setDelegate {
// You may want to NSLog here something to see, if the setter is called
  self.delegate = self; 
}

- (id <UITextFieldDelegate) getDelegate {
  return self;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
  //Do your stuff here 
  return YES;
}

@end