6

So far, I used to create custom nibs to make my cell as I wanted but this time, the height of a cell will change from one to another so that I can't create a fixed-size cell's nib.

So I decided to create it programmatically ... Is the way below the good way to achieve it ?

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        UILabel *pseudoAndDate = [[UILabel alloc] initWithFrame:CGRectMake(0.0,0.0,320.0,20.0)];
        [pseudoAndDate setTag:1];
        [cell addSubview:pseudoAndDate];
        [pseudoAndDate release];
    }

    CommentRecord *thisRecord = [comments objectAtIndex:[indexPath row]];

    UILabel *label = (UILabel *)[cell viewWithTag:1];
    [label setText:[NSString stringWithFormat:@"%@ | %@",thisRecord.author,thisRecord.date]];

    return cell;
}

or .. am i missing something here ? Cause so far it doesn't seem to work ;)

Thanks,

Gotye.

casperOne
  • 73,706
  • 19
  • 184
  • 253
gotye
  • 958
  • 2
  • 14
  • 33

3 Answers3

0

Why create a label when you don't need to? Use the UITableViewCell's label.

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

    static NSString *CellIdentifier = @"Cell";

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

    CommentRecord *thisRecord = [comments objectAtIndex:[indexPath row]];

    cell.textLabel.text = [NSString stringWithFormat:@"%@ | %@",thisRecord.author,thisRecord.date];

    return cell;
}
Nate Symer
  • 2,185
  • 1
  • 20
  • 27
0

If your problem is that the height varies from cell to cell you can use the method:

https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDelegate/tableView:heightForRowAtIndexPath:

From UITableViewDelagate to achieve it

mspapant
  • 1,860
  • 1
  • 22
  • 31
0

New link for custom UITableViewCell programmatically Apple Documentation UITableViewCell

gotye
  • 958
  • 2
  • 14
  • 33
  • Note that [link-only answers](http://meta.stackoverflow.com/tags/link-only-answers/info) are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference – kleopatra Sep 18 '15 at 07:13