简体   繁体   English

填充表格视图单元格

[英]Populating a table view cell

I currently have an dictionary containing 2 objects with separate keys, and I want to populate a table view cell with each object respectively. 我目前有一个包含2个带有单独键的对象的字典,我想分别用每个对象填充一个表格视图单元格。 So say for example my dictionary has 2 objects one with the key north and another object with the key south. 例如,假设我的字典有2个对象,其中一个键为北,而另一个对象为键南。 Now I want the table view to have 2 cells one containing north and one containing south. 现在,我希望表格视图有2个单元格,其中一个包含北,另一个包含南。 How would I go about doing that? 我将如何去做? so far i tried the code below but that only overrides it. 到目前为止,我尝试了下面的代码,但这仅将其覆盖。

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

    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
    }

    NSMutableDictionary *news = (NSMutableDictionary *)[feeds objectAtIndex:indexPath.row];
    [cell.textLabel setText:[news objectForKey:@"frstDirection"]];
    [cell.textLabel setText:[news objectForKey:@"secDirection"]];

    return cell;
}

If you are sure you have only two objects, you simply can use this: 如果确定只有两个对象,则可以使用以下方法:

NSMutableDictionary *news = (NSMutableDictionary *)[feeds objectAtIndex:indexPath.row];
if(indexPath.row==0){
     [cell.textLabel setText:[news objectForKey:@"frstDirection"]];
}else if(indexPath.row==1){
    [cell.textLabel setText:[news objectForKey:@"secDirection"]];
}

put if condition , if(indexPath.row % 2 == 0) then first direction else second direction. 如果条件为if,则将if(indexPath.row%2 == 0)放在第一个方向,否则放在第二个方向。 In this way you will alternate cells with first then second . 这样,您将用第一个然后第二个替换单元格。

In your case, you are trying to set value for cell twice so every time last value you will get as uitableviewcell. 在您的情况下,您尝试为单元格设置两次值,因此每次上一次获得的值都将作为uitableviewcell。

So try following code before [cell.textLabel setText:[news objectForKey:@"frstDirection"]]; 因此,请在 [cell.textLabel setText:[news objectForKey:@“ frstDirection”]]] 之前尝试以下代码

NSMutableString *teststring = [NSMutableString string];
[teststring appendString:[news objectForKey:@"frstDirection"]];
[teststring appendString:[news objectForKey:@"secDirection"]];
[cell.textLabel setText:teststring];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM