2012-04-19 71 views
0

我有點困惑如何使用IndexPath將行添加到TableView中。 在第i個INIT:從其他類的NSIndexPath到UITableView

tableView = [[UITableView alloc] initWithFrame:self.view.bounds]; 

    //rows code here 

    [self.view addSubview:tableView]; 

現在,這兩者之間我想一些行添加到我的表視圖。我有一個NSStrings包含元素名稱的NSArray。

所以我試試這個:

[[self tableView] beginUpdates]; 
[[self tableView] insertRowsAtIndexPaths:(NSArray *)myNames withRowAnimation:UITableViewRowAnimationNone]; 
[[self tableView] endUpdates]; 

然後我讀過,我首先應該以某種方式加入這UITableViewDataSource。所以我宣佈它錯了?我要求,因爲我寧願避免不必要的傳遞數據。

+2

看看這篇文章:http://stackoverflow.com/a/4022844/1228534 – graver 2012-04-19 14:11:42

回答

1

表格視圖的想法 - 以及MVC中的大多數視圖 - 是它們反映了模型的狀態。所以,是的,如你所說,有你的數據源保持一個數組:

@property (strong, nonatomic) NSMutableArray *array; 

變更這個數組:

[self.array addObject:@"New Object"]; 

記錄哪些行已經改變了......

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.array count]-1 inSection:0]; 
NSArray *myNames = [NSArray arrayWithObject:indexPath]; 

然後讓表格視圖知道您使用您發佈的代碼的模型是不同的...

[[self tableView] beginUpdates]; 
[[self tableView] insertRowsAtIndexPaths:myNames withRowAnimation:UITableViewRowAnimationNone]; 
[[self tableView] endUpdates]; 
+0

但我應該有什麼樣的數據在數組中顯示行? – Kuba 2012-04-19 14:23:01

+1

這完全取決於你。在cellForRowAtIndexPath:(NSIndexPath *)中,表視圖要求數據源配置表格單元格。這是應用程序設置字符串或圖像或其他內容的地方_represents_該模型,並將它們放入表格單元格中。在上面的示例代碼的情況下,數組是一個字符串數組,所以翻譯非常直接:cell.textLabel.text = [self.array objectAtIndex:indexPath.row]; – danh 2012-04-19 14:29:10

+0

哦,那太酷了:)謝謝;) – Kuba 2012-04-19 14:32:28

1

AFAIK這不是一個很好的方式來添加數據到UITableView。 我誤解你想幹什麼,在這兩種情況下,你需要設置你的tableview的數據源是這樣的:

tableView = [[UITableView alloc] initWithFrame:self.view.bounds]; 

[tableView setDataSource:self]; 

[self.view addSubview:tableView]; 

然後,你需要實現UITableViewDataSource協議(可能的UITableViewDelegate)。您將要實現以下數據源的方法:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [myNames count]; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithCellStyleDefault [email protected]"MyIdentifier"] autorelease]; 
    [[cell textLabel] setText:[myNames objectAtIndex:[indexPath row]]]; 
    return cell; 
} 

你可能想在重用標識讀了,這是必要的,以確保您順利的表滾動不佔用太多的內存。