How to submit UIView from UITableViewCell


In my app I have a UITableViewCell with a button in it.

- (void)buttonPressed:(id)sender {
    UIView *test = [[UIView alloc] initWithFrame:CGRectMake(self.frame.origin.y+5, self.frame.origin.x+53, 200, 200)];
    test.backgroundColor = [UIColor redColor];
    test.layer.cornerRadius = 15.0f;
    test.layer.masksToBounds = YES;
    [self addSubview:test];

However, this red view is presented behind the section headers. What's the best way to add it to the view from inside the UITableViewCell in a proper way?

Get the cell you want to add it to, and then use

[cell.contentView addSubview: test];

You can get the cell from the button's frame.origin by converting the point to the table view's coordinate system and using the UITableView method indexPathForRowAtPoint. That code might looks like this:

- (NSIndexPath *) indexPathForView: (UIView*) view;
  CGPoint viewCenter = CGPointMake(
  viewCenter = [self.tableView convertPoint: viewCenter fromView: view];
  NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: viewCenter];
  return indexPath;

Or better yet, as an extension on UITableView:

@implementation UITableView (indexPathForCellContainingView)

- (NSIndexPath *) indexPathForCellContainingView: (UIView *) view;
  //get the view's center point (which will be in it's parent view's coordinate system
  //And convert it to the table view's coorindate system
  CGPoint viewCenter = [self convertPoint: fromView: view.superview];

  //Ask the table view which cell's index path contains that point.
  return [self indexPathForRowAtPoint: viewCenter];