Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On iOS, what is the difference between adding a subview to a UITableViewCell object "cell" vs to "cell.contentView"?

In the following code, if we do [cell addSubview: someLabel] vs [cell.contentView addSubview: someLabel], they seem to work the same. Is there any difference doing one or the other? (the custom cell in the real code is adding UIImageView and UILabel) (UIView, on the other hand, doesn't have contentView, so we don't need to add subview to its contentView. UITableViewCell is a subclass of UIView by the way)

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

    UITableViewCell *cell = nil;

    if ([tableView isEqual:self.songsTableView]){

        static NSString *TableViewCellIdentifier = @"MyCells";

        cell = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];

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

        // ...  some code to create a UILabel (not shown here)

        [cell addSubview: someLabel];  // vs using [cell.contentView addSubView: ...]
like image 941
nonopolarity Avatar asked Aug 23 '12 02:08

nonopolarity


1 Answers

I believe If I am not wrong, the contentView is a subview of UITableViewCell.

If you look at this page here, you can see there are actually 3 subviews in a UITableViewCell

I think by default, the Editing Control is hidden until you enter edit mode for a table in which case, the Editing Control appears (the minus button left of each row) and your contentView gets resized and pushed to the right. This is probably what gives the "proper animation" effect mentioned by the other answer.

To test the difference, try adding a subview such as UILabel with text, to the cell rather than the cell.contentView. When you add it to cell rather than cell.contentView and you enter edit mode for your table, I believe your UILabel will not resize, you will see the edit button ontop/below the minus sign button.

like image 159
Zhang Avatar answered Sep 29 '22 08:09

Zhang