如何使用Dictionary为单元格设置标题

时间:2013-05-04 06:33:27

标签: iphone ios uitableview

我想使用NSDictionary而不是单元格数组。

以下是我的代码:

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

         UITableViewCell *cell=[[UITableViewCell alloc]  initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
        //Add the Bg Image to the cell
         //Add the Label
         UILabel *cellTitle=[[UILabel alloc]initWithFrame:CGRectMake(15, 7, 300, 30)];
         [cellTitle setBackgroundColor:[UIColor clearColor]];
         [cellTitle setFont:[UIFont fontWithName:@"Helvetica-Bold" size:12]];
         [cellTitle setTextColor:[UIColor darkGrayColor]];
         [cellTitle setText:[[cellArray objectAtIndex:indexPath.section]             objectAtIndex:indexPath.row]];
         [cell.contentView addSubview:cellTitle];
         return  cell;

       }

2 个答案:

答案 0 :(得分:0)

NSDictionary *dictionary1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"ABC",@"Name",@"12",@"Age", nil];

NSDictionary *dictionary2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"DEF",@"Name",@"14",@"Age", nil];

NSDictionary *dictionary3 = [[NSDictionary alloc] initWithObjectsAndKeys:@"GHI",@"Name",@"16",@"Age", nil];

NSDictionary *dictionary4 = [[NSDictionary alloc] initWithObjectsAndKeys:@"JKL",@"Name",@"18",@"Age", nil];

NSArray *array = [[NSArray alloc] initWithObjects:dictionary1,dictionary2,dictionary3,dictionary4, nil];

现在在cellForRowAtIndexPath中:

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

     UITableViewCell *cell=[[UITableViewCell alloc]  initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    //Add the Bg Image to the cell
     //Add the Label
     UILabel *cellTitle=[[UILabel alloc]initWithFrame:CGRectMake(15, 7, 300, 30)];
     [cellTitle setBackgroundColor:[UIColor clearColor]];
     [cellTitle setFont:[UIFont fontWithName:@"Helvetica-Bold" size:12]];
     [cellTitle setTextColor:[UIColor darkGrayColor]];
     [cellTitle setText:[[array objectAtIndexPath:indexPath.row] objectForKey:@"Name"]];
     [cell.contentView addSubview:cellTitle];
     return  cell;

   }

也在numberOfRowsInSection中:

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

答案 1 :(得分:0)

您可以使用更新的语法

NSDictionary *dict = @{@"key" : @"value", @"key2" : @"value2"};
NSDictionary *dict2 = @{@"key" : @"value", @"key2" : @"value2"};

NSArray *array = @(dict, dict2);