clipsToBounds and masksToBounds in grouped UITableViewCell

conorgriffin picture conorgriffin · Feb 20, 2013 · Viewed 8k times · Source

I'm trying to get my UITextView's corners to be masked by the rounded corners of the grouped UITableViewCell that contains it. Here's a screenshot of the cell as it currently stands

UITextView inside grouped UITableViewCell

Here's some of the code I'm using to try to prevent the corners from overlapping my cells borders. I tried both

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

and

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

This is obviously not working, what am I missing?

Answer

Sam Toizer picture Sam Toizer · Sep 6, 2013

I'm pretty sure that you can't mask the corners this way. The cell's backgroundView is an image for a grouped UITableView so there's no sense of masking.

A possible solution to the problem would be to round the corners yourself. This is a little tricky since you only want to round the top corners of the top cell and the bottom corners of the bottom cell. Fortunately, @lomanf posted a great solution to rounding arbitrary corners here: Round two corners in UIView. Using his MTDContextCreateRoundedMask method, we can achieve our goal.

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