如何在按下按钮后将UITextField插入UITableView

时间:2013-03-30 16:09:31

标签: objective-c uitableview uitextfield

在主视图应用程序中,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]; 

谢谢

2 个答案:

答案 0 :(得分:0)

考虑这个问题的方法是模型 - 视图 - 控制器(MVC)。 _objects是表示用户认为在表中的任何内容的模型。说这是一个待办事项列表,然后对象可以是你创建的NODbject子类的数组,如TodoItem。

您可以将新的TodoItem插入_objects,然后告诉您的表(MVC中的“视图”)它的模型已更改。您可以使用reloadData不精确地执行此操作,或者以代码建议的更有针对性的方式执行此操作,调用insertRowsAtIndexPaths - 但该调用必须夹在tableView beginUpdatesendUpdates之间。

您可以在cellForRowAtIndexPath中的代码中添加textFields,也可以在storyboard中的单元格原型中添加。您的表视图数据源应始终引用对象...即numberOfRows个答案self.objects.countcellForRowAtIndexPath得到:

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

并使用该项的属性初始化textField的文本。此外,顺便提一下,对象应该这样声明:

@property(strong,nonatomic) NSMutableArray *objects;

...您的代码几乎应该引用self.objects(不是_objects)。在第一个插入上初始化它太晚了,因为只要它可见,表就需要它立即生效。通常,一个好的做法是“懒惰”初始化取代合成的吸气剂......

- (NSMutableArray *)objects {

    if (!_objects) {    // this one of just a few places where you should refer directly to the _objects
        _objects = [NSMutableArray array];
    }
    return _objects;
}

答案 1 :(得分:0)

您可能会发现在这里使用免费的Sensible TableView框架非常有帮助。下面是一些示例代码,用于说明如何使用框架执行此操作:

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

对于这些类型的情况非常方便。