2013-05-04 68 views
0

我想使用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; 

     } 

回答

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]; 
    } 
0

您可以使用新的语法像这样

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

NSArray *array = @(dict, dict2); 
相关问题