Question

I have a custom UIView subclass Leaderboard which itself contains a tableview tblLeaderboard. The interface was created with a xib. Additionally, I have a UITableViewCell subclass LeaderboardCell which also has a xib. I'm having trouble registering the cell in the tableview.

Here's what I tried, first I registered the nib with the tableview:

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        leaderInfo = [NSMutableArray array];
        tblLeaderboard.dataSource=self;
            [tblLeaderboard registerNib:[UINib nibWithNibName:@"LeaderboardCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"leaderboardCell"];

    }
    return self;
}

Then when initializing the cell I have:

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

    static NSString *CellIdentifier = @"leaderboardCell";

    LeaderboardCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil) {
        cell = [[LeaderboardCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:CellIdentifier];
    }

//ADDED THIS IN CASE DEFAULT CELL WAS LOADED
 cell.textLabel.text = [[leaderInfo objectAtIndex:indexPath.row] objectForKey:@"name"   ];
    cell.name.text = [[leaderInfo objectAtIndex:indexPath.row] objectForKey:@"name"];        
    cell.score.text = [[[leaderInfo objectAtIndex:indexPath.row] objectForKey:@"score"] stringValue];

    return cell;
} 

The cell doesn't load the nib. It just makes a custom cell (the default cell loads the name and score properly, so I know the datasource is working fine).

I'm not sure if I'm getting in trouble here for using a UIView and not a ViewController to control my UITableView?

Was it helpful?

Solution

I don't really have alot of experiences with xibs, but in my old project I did it this way:

    static NSString *leaderBoardIdentifier = @"leaderboardCell"; //cell identifier same name as identifier in xib cell's attribute inspector
    LeaderboardCell *cell = (LeaderboardCell *)[tableView dequeueReusableCellWithIdentifier:leaderBoardIdentifier];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:leaderBoardIdentifier owner:self options:nil];
        cell = [nib objectAtIndex:0];

    }

I have my cell's xib file with h/m files. In my .h I've just connected elements from xib.

initWithStyle and setSelected methods in cell class have default code in them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top