clipsToBounds和masksToBounds在分组的UITableViewCell中

con*_*fin 6 uikit cglayer ios quartz-core

我试图让我UITextView的角落被UITableViewCell包含它的分组的圆角掩盖.这是目前单元格的屏幕截图

UITextView内置分组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];
Run Code Online (Sandbox Code Playgroud)

cell.layer.masksToBounds = YES;
cell.contentView.layer.masksToBounds = YES;
detailTextView.clipsToBounds = YES;
[cell addSubview:detailTextView];
Run Code Online (Sandbox Code Playgroud)

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

小智 0

我很确定你不能用这种方式掩盖角落。该单元格backgroundView是分组的图像UITableView,因此没有遮蔽的感觉。

解决这个问题的一个可能的办法是自己解决问题。这有点棘手,因为您只想圆化顶部单元格的顶角和底部单元格的底角。幸运的是,@lomanf 在这里发布了一个圆角任意角的绝佳解决方案:Round Two Corner 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;
}        
Run Code Online (Sandbox Code Playgroud)