0

我希望 UITableViewCell 中的 CellTextField 只接受数字字符。我以编程方式创建 UITableViewCells,如下所示:

    -(UITableViewCell*) getCellContentView: (NSString*) cellIdentifier {

        ...

        UITableViewCell *cell = [[UITableViewCell alloc] initWithFrame:cellFrame reuseIdentifier:cellIdentifier];

        ... 

        CellTextField *txt;  
        txt = [[CellTextField alloc] initWithFrame:amountFrame];

        ... //here we should setup a delegate or similar to handle char validation for txt

        [cell.contentView addSubview:txt];
        return cell;
    }

对于 UITextField 组件,我们有一个委托“shouldChangeCharactersInRange”,但我找不到 CellTextFields 的等价物。

4

1 回答 1

1

试试这个

。H

  @interface YourClass : ParentClass <UITextFieldDelegate>{
  NSNumberFormatter *integerNumberFormatter;
  }
  @end

.m

-(void)viewDidLoad
{
      [integerNumberFormatter setMaximumFractionDigits:0];
       yourTextField.delegate = self;
}

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

    NSString* proposedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSNumber *proposedNumber = [integerNumberFormatter numberFromString:proposedString];
    if (proposedNumber) {
        NSString *integerString = [integerNumberFormatter stringFromNumber:proposedNumber];
        if ([integerString isEqualToString:proposedString]) {
            // proposed string is an integer
            return YES;
        }
    }

    return NO;
}
于 2012-08-15T10:47:14.123 回答