2013-01-22 32 views
0

我有5個對象的NSArray。多節UITableView和NSArray

NSArray *tmpArry2 = [[NSArray alloc] initWithObjects:@"test1", @"test2", @"test3", @"test4", @"test5",nil]; 

我有4個部分(見截圖)

我想要做的就是展示

  • test1的在首節
  • TEST2和TEST3在第2節
  • test4 in 3rd section
  • test5 in 4th section

下面是我對他們每個人的index.row和index.section問題從

indexPath.row: 0 ... indexPath.section: 0 
indexPath.row: 0 ... indexPath.section: 1 
indexPath.row: 1 ... indexPath.section: 1 
indexPath.row: 0 ... indexPath.section: 2 
indexPath.row: 0 ... indexPath.section: 3 

我希望用indexPath.section去在tmpArry2值達到,但我不能當然我該怎麼做。我想創建一個全局靜態int計數器= 0;並不斷增加它在cellForRowAtIndexPath但問題是,如果我上下滾動的值不斷跳轉單元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    //NSLog(@"Inside cellForRowAtIndexPath"); 

    static NSString *CellIdentifier = @"Cell"; 

    // Try to retrieve from the table view a now-unused cell with the given identifier. 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    // If no cell is available, create a new one using the given identifier. 
    if (cell == nil) 
    { 
     // Use the default cell style. 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    NSLog(@"indexPath.row: %d ... indexPath.section: %d ...", indexPath.row, indexPath.section); 

//this will not give me right results 
//NSString *titleStr2 = [tmpArry2 objectAtIndex:indexPath.section]; 


} 

enter image description here

回答

4

下面的代碼應該幫助,但我不明白你爲什麼在tmpArry2和方法的cellForRowAtIndexPath有countDownArray職稱?我假設你在你的代碼中的某處重命名它。

如果將以下代碼放入cellForRowAtIndexPath方法中,它應該可以工作。

NSInteger index = 0; 
for (int i = 0; i < indexPath.section; i++) { 
    index += [self tableView:self.tableView numberOfRowsInSection:i]; 
} 
index += indexPath.row; 
cell.textLabel.text = [countDownArray objectAtIndex:index]; 
+0

對不起 - 我有一個錯字。當我把它發佈在這裏時,我通常會啞口無言。我錯過了一些變數 –

+0

固定錯字,對不起:) – Mert

+0

謝謝你的出色簡單的答案!奇蹟般有效 –

0

我認爲你需要改變tmpArry2的結構,讓子數組 - 這是一個常用的方法來做章節。因此,陣列應該是這樣的(使用新的符號爲數組):

NSArray *tmpArry2 = @[@[@"test1"], @[@"test2", @"test3"], @[@"test4"], @[@"test5"]]; 

這爲您提供了4個對象,每個是一個數組的數組。然後在你的數據源方法,你會這樣做:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return tmpArry2.count; 
} 

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    cell.textLabel.text = tmpArry2[indexPath.section][indexPath.row]; 
    return cell; 
}