动态TextField应仅接受数字字符

时间:2016-10-26 03:20:54

标签: ios objective-c uitextfield

我动态创建了textfield,就像15个文本字段一样。点击下一步按钮,我想检查用户是否输入了数字字符。请帮我这样做。我知道要做什么这是在故事板中创建的textfield。但我不知道通过编程动态文本字段。

这是我的代码,

 //Creating TextField

    UITextField *metaData_txt = [[UITextField alloc]init];
    metaData_txt.frame = CGRectMake(xPosOfTxt,yPosOfTxt , widthOfTxt, heightOfTxt);
    metaData_txt.layer.cornerRadius = 5;
    metaData_txt.layer.borderWidth =1.0;
    metaData_txt.layer.borderColor = [UIColor blackColor].CGColor;
    metaData_txt.tag = (txtTagBaseVaue +i);
       [self.metaData_txt setDelegate:self];       
          [self.sub_View addSubview:metaData_txt];

..点击下一个按钮

时检查数字数字字符
-(IBAction)next:(id)sender {
    NSArray *subviews = [self.sub_View subviews];

    for (UIView *newView in subviews) {
        if([newView isKindOfClass:[UITextField class]])
        {

              NSInteger tag = newView.tag;
            int index = tag - 100;


            FieldData *fieldData = [self.metaDataArray objectAtIndex:index];
       if (textField.text.length == 0) {

                     [self.view makeToast:label duration:1.0 position:CSToastPositionCenter];
                    NSLog(@"enter characters");

                }


                else if (textField.text.length > 0)
                {
               NSString *feildValue  = [self formatTypeToString:fieldData.fieldAttribute];
                    NSString *numeric = @"NUMERIC";

                    if (feildValue == numeric) {


                        [self textField:textField shouldChangeCharactersInRange:<#(NSRange)#> replacementString:<#(nonnull NSString *)#>];


                    }

我也编写了shouldchangechractersin范围方法: 我在调用下面的方法

时,不要给我的范围和字符串
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
   {
    if (!string.length)
    return YES;

if (textField)
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSString *expression = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:nil];
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
                                                        options:0
                                                          range:NSMakeRange(0, [newString length])];
    if (numberOfMatches == 0)
        return NO;
}
return YES;
}

请帮我这样做。
提前致谢!!!

0 个答案:

没有答案