0

在主视图应用程序中,xcode 生成带有表格视图和加号按钮的就绪应用程序。我想将该按钮更改为添加一个新单元格,但不是默认情况下的日期。我想添加两个文本字段,例如 label->textfield、label->textfield。

在代码中我有这个:

- (void)viewDidLoad{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self     action:@selector(insertNewObject:)];
    self.navigationItem.rightBarButtonItem = addButton;
    self.detailViewController = (GCDetailViewController *) [[self.splitViewController.viewControllers lastObject] topViewController];
}  

和功能:

- (void)insertNewObject:(id)sender{    
    if (!_objects) {
        _objects = [[NSMutableArray alloc] init];
    }    
    [_objects insertObject:[UITextField alloc] atIndex:0];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 

谢谢你

4

2 回答 2

0

考虑这个问题的方法是模型-视图-控制器 (MVC)。 _objects是您的模型代表用户认为表中的任何内容。假设它是一个待办事项列表,那么对象可以是您创建的 NSObject 子类的数组,例如 TodoItem。

You would insert new TodoItems into _objects, then tell your table (the "View" in MVC) that it's model has changed. You can do that imprecisely using reloadData, or in a more targeted fashion as your code suggests, calling insertRowsAtIndexPaths - but that call must be sandwiched between tableView beginUpdates and endUpdates.

You can add textFields in code in your cellForRowAtIndexPath, or in the cell prototype in storyboard. Your table view datasource should always refer to objects... i.e. numberOfRows answers self.objects.count, cellForRowAtIndexPath gets:

TodoItem *item = [self.objects objectAtIndexPath:indexPath.row];

and uses that item's properties to initialize the textField's text. Also, incidentally, objects should be declared like this:

@property(strong,nonatomic) NSMutableArray *objects;

...and your code should refer to self.objects almost everywhere (not _objects). Initializing it on the first insert is too late, because the table needs it to be valid right-away, as soon as it's visible. Usually, a good practice is a "lazy" init replacing the synthesized getter...

- (NSMutableArray *)objects {

    if (!_objects) {    // this one of just a few places where you should refer directly to the _objects
        _objects = [NSMutableArray array];
    }
    return _objects;
}
于 2013-03-30T16:34:45.907 回答
0

You might find using the free Sensible TableView framework really helpful here. Here is some sample code to illustrate how you'd do this using the framework:

- (void)insertNewObject:(id)sender{ 
   SCTableViewSection *section = [self.tableViewModel sectionAtIndex:0];
   [section addCell:[SCTextFieldCell cellWithText:@"Enter Text"]];
}

Comes in really handy for these types of situations.

于 2013-03-30T22:16:54.960 回答