grouped UITableViewCell中的clipsToBounds和masksToBounds

6
我正在尝试让我的UITextView的角被包含它的分组UITableViewCell的圆角所遮蔽。下面是当前单元格的截图。

UITextView inside grouped UITableViewCell

这是我用来防止角落重叠单元格边框的部分代码。我尝试了两种方法:
cell.contentView.layer.masksToBounds = YES;
cell.layer.masksToBounds = YES;  //tried this as a test, still doesn't work
detailTextView.clipsToBounds = YES;
[cell.contentView addSubview:detailTextView];

并且

cell.layer.masksToBounds = YES;
cell.contentView.layer.masksToBounds = YES;
detailTextView.clipsToBounds = YES;
[cell addSubview:detailTextView];

这显然不起作用,我错过了什么?


你尝试过 cell.clipsToBounds = YES; 吗? - Patrick
1
你的contentView边界比cell的边界大,因此裁剪contentView无法解决问题 - 你必须裁剪到cell。 - Pfitz
1
你使用故事板吗?我认为你只需要在单元格上勾选剪辑子视图,但我不确定如何在代码中实现。 - Patrick
我开始觉得,分组的UITableViewCell中的圆角可能实际上并不是边界,而只是使单元格看起来漂亮的位图。 - conorgriffin
几个想法 - 你试过 cell.contentView.clipsToBounds = YES; 吗?我猜你已经试过了,但是我在代码中没有看到它。你可能需要基于 cell.backgroundView 创建一个遮罩层。不过要小心这种方法,因为它可能会降低你的帧率,特别是在滚动时。 - Mike
显示剩余3条评论
2个回答

0

我也遇到了同样的问题。

不同之处在于我使用的是普通样式,并且我试图使每个单元格都有圆角。最终,我成功了,以下是我的方法:

1. 将以下代码放入自定义tableViewCell的awakeFromNib方法中

    [cell.layer setMasksToBounds:YES];
    [cell.layer setCornerRadius:5.0];

2. 将自定义的TableViewCell的contentView的背景色设置为白色,然后将tableView的背景色设置为透明色。就这样。


0

我相信你不能用这种方式遮盖角落。单元格的backgroundView是分组UITableView的图像,因此没有遮罩的感觉。

解决问题的一个可能的方法是自己将角落变圆。这有点棘手,因为你只想将顶部单元格的顶部角和底部单元格的底部角变圆。幸运的是,@lomanf在这里发布了一个关于圆角的绝妙解决方案:Round two corners in UIView。使用他的MTDContextCreateRoundedMask方法,我们可以实现我们的目标。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Other cell instantiation

    // First cell in section
    if (indexPath.row == 0) {
        [self roundTopOrBottomCornersOfCell:cell top:YES];       
    }
    // Last cell in section
    else if (indexPath.row == tableView.numberOfRowsInSection:indexPath.section-1) {
        [self roundTopOrBottomCornersOfCell:cell top:NO];
    }
}

// Modified from the second part of @lomanf's Solution 1
- (void)roundTopOrBottomCornersOfCell:(UITableViewCell*)cell top:(BOOL)top {
        // Set constant radius
        CGFloat radius = 5.0;

        // Create the mask image you need calling @lomanf's function
        UIImage* mask;
        if (top) {
            mask = MTDContextCreateRoundedMask(self.view.bounds, radius, radius, 0.0, 0.0);
        }
        else {
            mask = MTDContextCreateRoundedMask(self.view.bounds, 0.0, 0.0, radius, radius);
        }

        // Create a new layer that will work as a mask
        CALayer* layerMask = [CALayer layer];            
        layerMask.frame = cell.bounds;

        // Put the mask image as content of the layer
        layerMask.contents = (id)mask.CGImage;

        // Set the mask layer as mask of the view layer
        cell.layer.mask = layerMask;
}        

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接