LDK LDK - 1 year ago 121
iOS Question

Add button to UITableViewCell's Accessory View

Goal: when a user selects a cell, a button is added to that cell. Within my didSelectRowAtIndexPath function I have the following:

UIButton *downloadButton = [[UIButton alloc] init];
downloadButton.titleLabel.text = @"Download";
[downloadButton setFrame:CGRectMake(40, 0, 100, 20)];
[[self.tableView cellForRowAtIndexPath:indexPath].accessoryView addSubview:downloadButton];
[[self.tableView cellForRowAtIndexPath:indexPath].accessoryView setNeedsLayout];

[downloadButton release];

Unfortunately that doesn't seem to do anything. Am I redrawing the cell correction? Do I need to add it another way?

Answer Source

Try this block of code instead of the block you provided above:

UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[downloadButton setTitle:@"Download" forState:UIControlStateNormal];
[downloadButton setFrame:CGRectMake(0, 0, 100, 35)];
[tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton;

This should display the button, but you will still need to hook up some kind of selector to it using addTarget. (I am not sure if listening in for the accessoryButtonTappedForRowWithIndexPath delegate will work in this case, try that first and see if it fires on your button press.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download