表视图在每个部分重复数据

时间:2013-12-09 16:54:38

标签: ios uitableview

我有一个包含许多部分的表格视图。当我在plist中添加数据时,它们会添加到正确的部分,但是当表格显示时,它看起来像这样;

表视图:

Section 1
  Note 1

Section 2
  Note 1
  Note 2

而不是第一部分中的注释1和第2部分中的注释2。

我在celForRowAtIndexPath中推测它的错误,但我不知道是什么。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath
{
cell.textLabel.text = [[self.notes objectAtIndex:indexPath.row] objectForKey:@"Title"];
cell.detailTextLabel.text = [[self.notes objectAtIndex:indexPath.row] objectForKey:@"Date"];
}    

更新 - NSLog of self,注意:

{ Category = Section 1; 
Date = "December 9, 2013"; 
Text = "Note 1 text"; 
Title = "Note 1"; }, 

{ Category = Section 2;
 Date = "December 9, 2013";
 Text = "Note 2 text";
 Title = "Note 2"; 
}

Plist链接:

http://i.stack.imgur.com/qrbfh.png

3 个答案:

答案 0 :(得分:1)

如果要在表格部分中显示数据,那么您的数组结构应该是这样的。 然后不需要任何硬编码比较。

( 
  (
    {key value pair}, 
    {key value pair}
  ),
  (
   {key value pair}, 
   {key value pair} 
  ), 
  ( 
   {key value pair}, 
   {key value pair}, 
   {key value pair}, 
   {key value pair}, 
   {key value pair}
  )
)

然后以这种方式访问​​:

cell.textLabel.text = [[[self.notes objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]objectForKey:@"Title"];

答案 1 :(得分:0)

在cellForRowAtIndexPath中考虑该部分:

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

    if (indexPath.section == 0){
        cell.textLabel.text = [[self.notes objectAtIndex:indexPath.row] objectForKey:@"Title"];
        cell.detailTextLabel.text = [[self.notes objectAtIndex:indexPath.row]     objectForKey:@"Date"];

    } else if (indexPath.section == 1){
    // do stuff speficic for section 1 (the second section)
    // ... 

    } 
}

答案 2 :(得分:0)

试试这个:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath (NSIndexPath *)indexPath{
        if (indexPath.section == 0){
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"Category =[cd] %@", @"Category 1"];
            NSArray * catArray = [self.notes filteredArrayUsingPredicate:pred];
            cell.textLabel.text = [[catArray objectAtIndex:indexPath.row] objectForKey:@"Title"];
            cell.detailTextLabel.text = [[catArray objectAtIndex:indexPath.row] objectForKey:@"Date"];

        } else if (indexPath.section == 1){
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"Category =[cd] %@", @"Category 1"];
            NSArray * catArray = [self.notes filteredArrayUsingPredicate:pred];
            cell.textLabel.text = [[catArray objectAtIndex:indexPath.row] objectForKey:@"Title"];
            cell.detailTextLabel.text = [[catArray objectAtIndex:indexPath.row] objectForKey:@"Date"];
        } 
    }

最后一个NSPredictate参数,例如:@“Category 1”,如果你想让它取决于用户,你的app逻辑应该是控制器。