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

Inserting button on tableview cell

Hello guys. Am trying to create UIButton programmatically in a table view cell. I have this json http://www.annalenawinter.se/app3/albums and when displaying all tracks in a table view. I would like to show a buy button when a song a is of type "buy" as show in the json link. The problem am getting is that when i scroll down the button disappear. http://pastebin.com/YFGvxrHz Any help will be appreciated.

4 Answers

You could add your button to you nib (or your cell in your storyboard) and then set the property hidden to YES or NO as you are configuring your cell in cellForRowAtIndexPath. There is also -(void)prepareForReuse that can be used for resetting values as you reuse your cells.

Thanks but the button keeps on disappearing every time I scroll down the list as the cells are reused. As for the prepareForReused method, I honestly do not understand it and how I can make it work with what am trying to achieve.

Try setting your hidden property to NO in prepareForReuse. So implement - (void)prepareForReuse in your TableViewController and set self.button.hidden = NO; and then of course set it to NO or YES according to your buy property when you configure the cell.

Yeeeeeeeeah :) Works like a charm ...Thanks so much. Struggled with this for a week and now its working n thanks to you. :)

Cool, glad I could help :)

Do you mind sharing the project so I can have a look? :)

Sure.. I have it here https://github.com/kenjox/Demo

I don't have too much time to look at it now, but I see the problem. You're using the "dequeueReusableCellWithIdentifier" which in itself, is fine. But, if you try to log out "NSLog(@"%ld", (long)indexPath.row);" in the "- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath" method. You'll see the cells are reused. Which means as soon as you scroll, the button you added to one cell will be placed in another.

Now I understand why but the question is, is there a way to make them stay? Any better approach to achieve this instead?

I usually do this programmatically, but I'll have a look later today ;) Maybe Amit Bijlani has a good solution in the mean time?

I will really appreciate if you will find time to look at it.. no pressure. To be honest I am out of ideas.