UITableView没有正确填充NSArray内容的部分

时间:2014-06-23 20:05:41

标签: ios objective-c arrays json uitableview

My Parse云代码使用以下结构将JSON发送回我的iOS应用程序:

enter image description here

我想要做的就是遍历这个并在UITableView中为这个matchCenterArray中的每个对象创建一个新的部分。

在这个例子中,数组中有三个对象,每个对象包含一个Top 3 NSDictionary,其值为3个项目的数组,每个项目都是另一个属性数组。正如您所看到的,我希望它设置为每个部分有3个单元格,每个单元格对应相应matchCenterArray个对象的前三个项目。然后,我希望它拉出每个项目的属性,并在每个单元格中显示为texLabeldetailTextLabel和缩略图。

我尝试使用for循环作为解决方案,但这会在数组的所有单元格中显示相同的项目。这可能是因为我只是循环遍历matchCenterArray对象,而不是另外循环遍历这些对象中的项目,如下所示:

cell.textLabel.text = [[[[_matchCenterArray  objectAtIndex:i] objectForKey:@"Top 3"] objectAtIndex:0]objectForKey:@"Title"];

我想要做的是将for循环嵌套在这个循环中,代替objectAtIndex:0,但是向for循环发送消息并不起作用。

MatchCenterViewController.m:

#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>

@interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *matchCenter;
@end

@implementation MatchCenterViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];

    self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
    self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-100);
    _matchCenter.dataSource = self;
    _matchCenter.delegate = self;
    [self.view addSubview:self.matchCenter];

    _matchCenterArray = [[NSArray alloc] init];
}

- (void)viewDidAppear:(BOOL)animated
{
    self.matchCenterArray = [[NSArray alloc] init];

    [PFCloud callFunctionInBackground:@"MatchCenterTest"
                       withParameters:@{
                                        @"test": @"Hi",
                                        }
                                block:^(NSArray *result, NSError *error) {

                                    if (!error) {
                                        _matchCenterArray = result;
                                        [_matchCenter reloadData];

                                        NSLog(@"Result: '%@'", result);
                                    }
                                }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _matchCenterArray.count;
}

//the part where i setup sections and the deleting of said sections

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 21.0f;
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 21)];
    headerView.backgroundColor = [UIColor lightGrayColor];

//    _searchTerm = [[self.matchCenterArray firstObject] objectForKey:@"Search Term"];

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 250, 21)];
//    headerLabel.text = [NSString stringWithFormat:@"%@", searchTerm];
//    headerLabel.font = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
//    headerLabel.textColor = [UIColor whiteColor];
    headerLabel.backgroundColor = [UIColor lightGrayColor];
    [headerView addSubview:headerLabel];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = section + 1000;
    button.frame = CGRectMake(300, 2, 17, 17);
    [button setImage:[UIImage imageNamed:@"xbutton.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:button];
    return headerView;
}



- (IBAction)deleteButtonPressed:(UIButton *)sender {
    NSLog(@"Search Term: '%@'", _searchTerm);

    [PFCloud callFunctionInBackground:@"deleteFromMatchCenter"
                       withParameters:@{
                                        @"searchTerm": _searchTerm,
                                       }
                                block:^(NSDictionary *result, NSError *error) {

                                    if (!error) {
                                        NSLog(@"Result: '%@'", result);
                                    }
                                }];
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     return 3;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Initialize cell
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        // if no cell could be dequeued create a new one
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }






    for (int i = 0; i<[_matchCenterArray count]; i++) {


    // populate dictionary with results

    //NSDictionary *matchCenterDictionary= [_matchCenterArray objectAtIndex:indexPath.row];

    // title of the item
    cell.textLabel.text = [[[[_matchCenterArray  objectAtIndex:i] objectForKey:@"Top 3"] objectAtIndex:0]objectForKey:@"Title"];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:12];

    // price of the item
    cell.detailTextLabel.text = [NSString stringWithFormat:@"$%@", [[[[_matchCenterArray  objectAtIndex:i] objectForKey:@"Top 3"] objectAtIndex:0]objectForKey:@"Price"]];
    cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];

    // image of the item
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[[[_matchCenterArray  objectAtIndex:i] objectForKey:@"Top 3"] objectAtIndex:0] objectForKey:@"Image URL"]]];
    [[cell imageView] setImage:[UIImage imageWithData:imageData]];
    //imageView.frame = CGRectMake(45.0,10.0,10,10);



    }

    return cell;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

2 个答案:

答案 0 :(得分:1)

忘记循环,委托方法已在迭代编号等于数据源计数的循环上运行。

<强> numberOfSectionsInTableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _matchCenterArray.count;
}

<强> numberOfRowsInSection

- (NSInteger)tableView:(UITableView *)tableView 
                                   numberOfRowsInSection:(NSInteger)section{
     return _matchCenterArray[section][@"Top 3"].count;
}

<强>的cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView 
                           cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // Initialize cell
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        // if no cell could be dequeued create a new one
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                                         reuseIdentifier:CellIdentifier];
    }

    // title of the item
    cell.textLabel.text = _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Title"];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:12];

    // price of the item
    cell.detailTextLabel.text = [NSString stringWithFormat:@"$%@", _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Price"];
    cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];

    // image of the item
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Image URL"]]];
    [[cell imageView] setImage:[UIImage imageWithData:imageData]];

    return cell;

}
  • 不要对您的数组进行编码,如果您的json发生更改,您的代码将需要更改。
  • 将来你应该考虑使用像SDWebImage这样的库来异步加载图像,以避免滞后。

答案 1 :(得分:0)

cellForRowAtIndexPath:

调用{p> numberOfRowsInSection:一次

您还需要添加numberOfSections

它应该是这样的:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Initialize cell
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        // if no cell could be dequeued create a new one
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // the following will set the cell attributes for cells in each section
    // to customize per section, use indexPath.section to get which section you are at

    // title of the item
    cell.textLabel.text = [[[[_matchCenterArray  objectAtIndex:indexPath.row objectForKey:@"Top 3"] objectAtIndex:0]objectForKey:@"Title"];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:12];

    // price of the item
    cell.detailTextLabel.text = [NSString stringWithFormat:@"$%@", [[[[_matchCenterArray  objectAtIndex:indexPath.row] objectForKey:@"Top 3"] objectAtIndex:0]objectForKey:@"Price"]];
    cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];

    // image of the item
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[[[_matchCenterArray  objectAtIndex:indexPath.row] objectForKey:@"Top 3"] objectAtIndex:0] objectForKey:@"Image URL"]]];
    [[cell imageView] setImage:[UIImage imageWithData:imageData]];

    return cell;
}

请参阅apple's tableView guide

相关问题