简体   繁体   中英

Changing the contentView when an Accessory button is tapped

I've subclassed UITableViewCell to display a UIImage and two UILabel subviews. In the view controller for the table view, in the method cellForRowAtIndexPath: I've enabled an accessory view via setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton .

Cells display correctly.

When I tap on the accessory disclosure button I want to replace the two label subviews with two different label subviews. My approach was the following:

  1. In the subclassed UITableViewCell , inside layoutSubviews , create the CGRect s for the "alternate" labels, position them in the same places as the two "original" label and hide them via setAlpha: ;
  2. When the disclosure button is tapped swap out the set of two label by adjusting their respective alphas.

The problem is I can't figure out what logic in layoutSubviews I'd use to know whether the accessory button has been tapped. I see that in the view controller accessoryButtonTappedForRowWithIndexPath: is called when that button is tapped and from there it seems like I would call layoutSubviews but can't figure out how to use that fact to accomplish what I'm trying to do.

Am I going about this all wrong? Instead of hiding/showing CGRect s with alpha should I simply be creating another subclass of UITableViewCell ?

When I tap on the accessory disclosure button I want to replace the two UILabel subviews with two different UILabel subviews.

I'll do the following. Create a public method in your UITableViewCell subclass like the following:

- (void)changeContentForCell;

In this method you could set the contentView as you prefer.

Then in your view controller implement

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    CustomCell* cCell = (CustomCell*)[tableView cellForRowAtIndexPath:indexPath];
    [cCell changeContentForCell];
}

This is a simple example for change the content. In my opinion you don't have to use layoutSubviews to add views.

Leave this logic in changeContentForCell and then call setNeedsLayout to change your layout. Maybe you could have a variable that tracks the state for your cell: normal state or modified state.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM