UITableView 动态部分



我正在使用使用动态部分的表视图,我有一个由部分标题组成的sectionArray和另一个包含所有部分的完整数据的数组,我无法弄清楚如何为每个部分编写行的单元格,因为它是动态的

代码为:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  return [appDelegate.sectionArray count];
}
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
  return [appDelegate.appNameArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
  UILabel *AppNameLabel=[[UILabel alloc]initWithFrame:CGRectMake(80, 0, 120, 30)];
  [AppNameLabel setBackgroundColor:[UIColor clearColor]];
  [AppNameLabel setText:[NSString stringWithFormat:@"%@",[appDelegate.appNameArray objectAtIndex:indexPath.row]]];
  [AppNameLabel setFont:[UIFont systemFontOfSize:14]];
  [cell.contentView addSubview:AppNameLabel];
  return cell;
}

在 appname 数组中,我有包含所有部分的数据,我需要为特定部分隔离,如何在单元格中制作行索引,请帮助。

提前谢谢。

无需为 sectionTitle 和 appName 创建两个不同的array。创建具有NSDictionary对象的源NSArrayNSDictionary对象包含 appName 数组作为 values 和 sectionTitle 作为key

sourceArray
(
 dictionaryObject1
 {
 key : sectionTitle,
 value : ( appName1,appName2,appName3)
 },
 dictionaryObject2
 {
 key : sectionTitle,
 value : ( appName1,appName2,appName3)
 },
.
.
.
)

首先,您的numberOfRowsInSection方法应如下所示:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arrayForSection = appDelegate.sectionArray[section];
    return [arrayForSection count];
}

之后修改cellForRow方法:

NSArray *arrayForSection = appDelegate.sectionArray[indexPath.section]
[AppNameLabel setText:[NSString stringWithFormat:@"%@",[arrayForSection objectAtIndex:indexPath.row]]];

您需要相应地更新数据源。只需通过枚举数组来动态编辑数组。就像您添加了一个部分一样,您应该在数组中动态添加部分详细信息。

NSArray *tempArray = [NSArray alloc] initWithArray:sectionArray];
for(int i = index; i<= (sectionArray.count-i-1); i++)
{
   if(i = index){
      [sectionArray replaceObjectAtIndex:i withObject:newSection]
   }
   else
   {
     sectionArray replaceObjectAtIndex:i withObject:[tempArray objectAtIndex: i-1];
   }
}

最新更新