Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Kieran Robinson
Kieran Robinson
9,411 Points

UIButton within a custom cell

Hi, I have a custom UITableViewCell that has an imageView property and a button (showBigPhotoButton) I want to be able to press on the button and present a view controller modally that contains the cells image (from its imageView) on a larger view. Similar to the view controller shown on Sam Soffes 'detailViewController' on the photoBombers project. My problem is that i can't present the viewController from within the custom cells class. Any help is greatly appreciated, Kieran

6 Answers

Mike Baxter
Mike Baxter
4,442 Points

Can you just pass your subclass of UITableViewCell a weak reference to the viewController (in this case, the UITableViewController, right?) after you initialize the custom cell? Your button can have a target-action pair with a method that tells your viewController to present a view controller modally.

Kieran Robinson
Kieran Robinson
9,411 Points

how would you do this? We can use the diary app as an example? the UITableViewCell is called EntryCell, the UITableViewController is called entryListViewController, within the cell there is an imageView called mainImageView and the button (showPhotoButton) will display whatever image is in the cells mainImageView on a new viewController thanks!

Ash Furrow
Ash Furrow
Treehouse Guest Teacher

It's a little more complicated, I'm afraid. You'd have to set up some kind of callback from each cell to the view controller so that it may present the new modal VC. So you'd need to declare a new delegate protocol and a new property on each cell that points to an object that conforms to that protocol.

Kieran Robinson
Kieran Robinson
9,411 Points

I have got it to work thanks to thomas' solution! Thank you

Thomas Nilsen
Thomas Nilsen
14,957 Points

Use a delegation pattern for this :)

Thomas Nilsen
Thomas Nilsen
14,957 Points

If you can share the project I can show you how you would go about doing this ;)

Kieran Robinson
Kieran Robinson
9,411 Points

Thank you so much Thomas!! That cleared it right up!