Ios 如何在UITableView中将单元格添加到自定义节
我的Ios 如何在UITableView中将单元格添加到自定义节,ios,objective-c,iphone,arrays,uitableview,Ios,Objective C,Iphone,Arrays,Uitableview,我的UITableView中有三个部分,当我创建要进入此UITableView的对象时,我想指定要进入哪个部分。我通过将它添加到三个数组中的一个来实现这一点。注意:所有对象最初都添加到称为对象的holderNSMutableArray中 for (Profile *p in self.objects) { if ([p.type isEqualToString:@"eol"]) { [self.eolobjects addObject:p];
UITableView
中有三个部分,当我创建要进入此UITableView
的对象时,我想指定要进入哪个部分。我通过将它添加到三个数组中的一个来实现这一点。注意:所有对象最初都添加到称为对象的holderNSMutableArray
中
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];
如果我单击(例如)任何节中的第一个对象,我将始终在对象数组的第一个索引处创建该项的对象,而不是填充我正在单击的节的数组的第一个索引中的对象。如果我将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;
}
你有两个解决方案
- 试试这个
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]