2015-02-08 58 views
0

我在UITableView三段,当我创建对象进入这个UITableView,我想指定我希望它进入哪个部分。我通过将它添加到三个数组中的一个来做到这一点。请注意,所有对象最初都被添加到名为对象的持有者NSMutableArray如何单元添加到自定义栏目中的UITableView

for (Profile *p in self.objects) { 
     if ([p.type isEqualToString:@"eol"]) { 
      [self.eolobjects addObject:p]; 
     } 
     else if ([p.type isEqualToString:@"ae"]) { 
      [self.aeobjects addObject:p]; 
     } 
     else if ([p.type isEqualToString:@"mw"]) { 
      [self.mwobjects addObject:p]; 
     } 

,就会出现问题,当我想原因请看到detailViewController

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    if ([[segue identifier] isEqualToString:@"showDetail"]) { 
     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; 
     Profile *object = self.objects[indexPath.row]; 
     [[segue destinationViewController] setDetailItem:object]; 

    } 
} 

因为线路的:

Profile *object = self.objects[indexPath.row]; 

如果我点击(例如)在任何部分中的第一对象,我会始终在objects数组的第一个索引处创建项目的对象,而不是在数组的第一个索引中填充我单击的部分的对象。如果更改self.objects我的三个其他阵列中的任何一个。

是否有细胞添加到部分更简单的方法在一个UITableView或者是有办法解决我的问题?由于

我的数据源的方法是这样的:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    // Return the number of sections. 
    return 3; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    if (section ==0) { 
     return @"Evolution of Life"; 
    } 
    else if (section==1){ 
     return @"Active Earth"; 
    } 
    else if (section==2){ 
     return @"Mineral Wealth"; 
    } 
    return @""; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    // Return the number of rows in the section. 
    switch (section) { 
     case 0: return self.eolobjects.count; break; 
     case 1: return self.aeobjects.count; break; 
     case 2: return self.mwobjects.count; break; 
    } 

    return 0; 
} 

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

    if (indexPath.section == 0) { 
     Profile *profile = self.eolobjects[indexPath.row]; 
     cell.textLabel.text = [profile name]; 
     return cell; 
    } 

    else if (indexPath.section ==1){ 
     Profile *profile = self.aeobjects[indexPath.row]; 
     cell.textLabel.text = [profile name]; 
     return cell; 
    } 

    else if (indexPath.section ==2){ 
     Profile *profile = self.mwobjects[indexPath.row]; 
     cell.textLabel.text = [profile name]; 
     return cell; 
    } 

    return cell; 
} 

回答

0

有两种解决方法

  • 试试这个

    Profile *object =nil; 
    switch (indexPath.) { 
        case 0: object = self.eolobjects[indexPath.row]; break; 
        case 1: object = self.aeobjects[indexPath.row]; break; 
        case 2: object = self.mwobjects[indexPath.row]; break; 
    } 
    
  • 或者你可以把所有的3个数组中一个阵列,并像这样轻松访问它们allObjects[indexPath.section][indexPath.row]

相关问题