Categories
iOS Work Note

Work Note: UIButton and UITableViewCell contentView

I am not sure why I see this behavior but I am sure someone smarter than I am can explain it. I am creating a custom table view cell derived from UITableViewCell. In the viewDidLoad method I’m adding, amongst other things, a UIButton to the cell.

All of the UILabels I added to the cell were added to the contentView and display just fine, but the UIButton’s I added to it don’t work properly, you can see them, but no events fire.

Here’s how I’m doing it:

[self.contentView addSubview:self.fancyButton];

That doesn’t work. However, adding the button to the view, does work:

[self.view addSubView:self.fancyButton];

According Apple’s documentation for UITableViewCell contentView:

The content view of a UITableViewCell object is the default superview for content displayed by the cell. If you want to customize cells by simply adding additional views, you should add them to the content view so they will be positioned appropriately as the cell transitions into and out of editing mode.

If I add the button using Interface Builder, it works as expected, but in this case I’m building the cell in code. At some point I need to dissect a prototype Interface Builder based UITableViewCell to see what it does. I would imagine it places all subviews in the view, not the contentView.

By Rob Fahrni

Husband / Father / Developer