[Solved] UILabel position in a UITableViewCell fails on the first try


If I do any complex layout in a UITableViewCell I try to keep it out of cellForRowAtIndexPath. One option is to do layout in - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath but I prefer to encapsulate layout in a custom UITableViewCell class.

Make your own UITableViewCell subclass. Create and add the custom button / label / view to the cell’s contentView in your init method, or create and add it lazily via an accessor property. Override layoutSubviews and postion the button as desired.

Something like this:

@implementation MyCustomCell

- (void) init
{
    self = [super initWithStyle: UITableViewCellStyleDefault reuseIdentifier: nil];
    if ( self != nil )  
    {
         _myButton = [[UIButton buttonWithType: UIButtonTypeRoundedRect] retain];
         [self.contentView addSubview: _myButton];
    }

    return self;
}

- (void) layoutSubviews
{
    [super layoutSubviews];

    // dynamic layout logic:
    if ( ... )
    {

         _myButton.frame = CGRectMake( 10, 10, 100, 30 );
    }
    else 
   {
         _myButton.frame = CGRectMake( 20, 10, 50, 30 );

   }
}

1

solved UILabel position in a UITableViewCell fails on the first try