2013-03-30 54 views
0

在主視圖中,應用程序xcode生成帶有表格視圖和加號按鈕的就緒應用程序。我想更改該按鈕來添加一個新的單元格,但不包含日期,因爲它是默認的。我想添加兩個文本字段,如label-> textfield,label-> textfield。如何在按下按鈕後將UITextField插入到UITableView中

在代碼中,我有這樣的:

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

謝謝

+0

格式化您的代碼..... –

+0

ok @AnoopVaidya – PurpleMonk

回答

0

的方式來思考,這是模型 - 視圖 - 控制器(MVC)。 _objects是代表用戶認爲表格中的任何內容的模型。說它是一個待辦事項列表,那麼對象可以是您創建的像TodoItem這樣的NSObject子類的數組。

您會將新的TodoItems插入_objects,然後告訴您的表(MVC中的「視圖」)它的模型已更改。您可以使用reloadData或以更具針對性的方式做到這一點,因爲您的代碼建議,調用insertRowsAtIndexPaths - 但該調用必須夾在tableView beginUpdatesendUpdates之間。

您可以在cellForRowAtIndexPath中的代碼中或在故事板中的單元格原型中添加textField。你的表視圖的數據源應始終參考對象...即numberOfRows回答self.objects.countcellForRowAtIndexPath得到:

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

,並使用該項目的屬性初始化文本框的文本。另外,順便說一句,對象應該聲明如下:

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

您可能會發現使用免費的明智的TableView框架真的在這裏有幫助。下面是一些示例代碼來說明你是如何做到這一點使用的框架:

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

進來非常方便,這些類型的情況。