Goal: when a user selects a cell, a button is added to that cell. Within my didSelectRowAtIndexPath function I have the following:
UIButton *downloadButton =
Its always best to add any views that you are adding to a cell to cell.contentView
.
Also try to check if the accessoryView is nil.
I had the same problem. Attempting to set the accessoryView to a UIButton which had an image caused it to not appear.
The trick was to call [UIButton sizeToFit]
, to ensure its frame is set properly.
Try This:
[[self.tableView cellForRowAtIndexPath:indexPath].contentView addSubview:downloadButton];
And remember to delete that button when the cell is being reused.
Here is my example for a the full solution to your request:
In my UITableViewCell subclass (I call it RNWNewItemCell):
-(void)configureCell...
{
// create the button
self.btnSeekDuplicate = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
// just make it yellow until we get our real image..
self.btnSeekDuplicate.backgroundColor = [UIColor yellowColor];
// add the handler for the button press
[self.btnSeekDuplicate addTarget:self
action:@selector(seekDuplicateButtonWasPressed)
forControlEvents:UIControlEventTouchUpInside];
// make it visible in the table cell...
[self setAccessoryView:self.btnSeekDuplicate];
}
- (void)seekDuplicateButtonWasPressed
{
do something...
}
In my Table Code that uses the cell...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
RNWNewItemCell *aNewItemCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifierForNewItemCell forIndexPath:indexPath];
[aNewItemCell configureCell...]
...
}
Note that accessoryButtonTappedForRowWithIndexPath is NOT called when you set the table cell's accessoryView. Probably because they assume you are using a view that responds to events.
Swift
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let accessoryButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as! UIButton
cell.accessoryView = accessoryButton
return cell
}
use this :
cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;