2012-08-15 25 views
0

我想有一個UITableViewCell中的CellTextField只接受數字字符。 我編程方式創建UITableViewCells這樣的:Obj-c/Cocoa touch:有UITableViewCell - CellTextField只接受數字字符?

-(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; 
    } 

因爲我們有一個委託「shouldChangeCharactersInRange」的UITextField組件,但我找不到CellTextFields相當。

回答

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; 
} 
+0

我將如何着手實際上與特定的(編程方式創建)CellTextField連接呢? – Wollan 2012-08-15 10:53:39

+0

我認爲CellTextField是一種UITextField,不是嗎? – janusbalatbat 2012-08-15 10:55:20

+1

CellTextField必須是UITextField的子類。在這種情況下,您可以將您的類註冊爲CellTextField實例的代理。 – 2012-08-15 11:06:52

相關問題