从数组向UITableView添加单元格

时间:2012-02-23 05:46:01

标签: ios uitableview uikit nsarray

我传递一个名为userArray的数组,它存储另一个带字符串的数组。这是我到目前为止,但我知道这是错的。有人能指出我正确的方向吗?

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

    static NSString *CellIdentifier = @"Cell";    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        cell = [[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
    }

    //Set Up Cell
    DataSingleton *sharedData = [DataSingleton sharedData];

    for (NSArray *array in sharedData.usersArray){
        cell.primaryLabel.text = [array objectAtIndex:1];
        cell.secondaryLabel.text = [array objectAtIndex:2];
        cell.profileImage = [UIImage imageNamed:@"111-user.png"];
        return cell;
    }
}

1 个答案:

答案 0 :(得分:1)

cellForRowAtIndexPath是一种UITableViewDataSource方法,它只询问单个单元格的数据。因此,您需要删除一个循环,并使用indexPath.row作为DataSingleton

中的数组索引,一次设置一个单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        cell = [[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
    }

    //Set Up Cell
    DataSingleton *sharedData = [DataSingleton sharedData];

    NSArray *array = [sharedData.usersArray objectAtIndex:indexPath.row];
    cell.primaryLabel.text = [array objectAtIndex:1];
    cell.secondaryLabel.text = [array objectAtIndex:2];
    cell.profileImage = [UIImage imageNamed:@"111-user.png"];
    return cell;   
}

此外,您应该实施tableView:numberOfRowsInSection:以返回[[[DataSingleton sharedData] usersArray] count]