如何从UITableViewCell呈现UIView

时间:2017-05-06 12:01:19

标签: ios objective-c uitableview uiview

在我的应用中,我有UITableViewCell,其中有一个按钮。

- (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];
}

但是,此红色视图显示在节标题后面。什么是以正确的方式从UITableViewCell内部添加到视图的最佳方式?

2 个答案:

答案 0 :(得分:0)

获取要添加的单元格,然后使用

[cell.contentView addSubview: test];

您可以通过将点转换为表格视图的坐标系并使用UITableView方法indexPathForRowAtPoint从按钮的frame.origin中获取单元格。该代码可能如下所示:

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

或者更好的是,作为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: view.center fromView: view.superview];

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

@end

答案 1 :(得分:-1)

你可以试试这个:

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