简体   繁体   中英

Nib prototype uitableviewcell cellForRowAtIndexPath:

Trying to set and access nib tableview cell. Basically the same as creating uitableview with a prototype tableviewcell and setting its identifier and accessing it through

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Fill table in with data
    static NSString *cellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }

Question is how would you do this as a nib. As nib IB doesn't have prototype option?

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

UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell"];

        MPMediaItem *song = [self.songsList objectAtIndex:indexPath.row];
        NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
        NSString *durationLabel = [song valueForProperty: MPMediaItemPropertyGenre];
        cell.textLabel.text = songTitle;
        cell.detailTextLabel.text = durationLabel;


    return cell;
}

-(void)viewDidLoad {
      [self.tableView registerNib:[UINib nibWithNibName:@"MusicViewController" bundle:nil] forCellReuseIdentifier:@"Cell"];
}

Create a custom tableviewCell with the nib file.After creation you have three files YourCustomCell.h YourCustomCell.m and YourCustomCell.xib

Add the IBOutlet in YourCustomCell.h and connect them in YourCustomCell.xib with respective labels.

Now in cellForRowAtIndexPath: add the following:

    YourCustomCell *yourCustomCell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell"];

    yourCustomCell.labelInCustomCell.textLabel.text = songTitle;
    yourCustomCell.detailsLabelInCustomCell.textLabel.text = durationLabel;

    return yourCustomCell;

Hope this help you.

You make your cell in the xib file and then in code (probably in viewDidLoad) register the nib with registerNib:forCellReuseIdentifier:. In cellForRowAtIndexPath, you just dequeue a cell with the same identifier that you passed to the register method. No need to put in the if (cell == nil) clause, because it will never be nil.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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