UITableViewCell 的子视图不能是圆的

UITableViewCell's subviews can't be round

我想创建一个具有一些圆形子视图的表视图作为 UIView。我设置了 UIView 的 layer.cornerRadius 和 clipsToBounds。但有些观点并不圆满。谁能帮我解决这个问题或给我一些建议?

我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * settCellID = @"settingCellID";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:settCellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:settCellID];

        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(100, 10, 20, 20)];
        view.layer.cornerRadius = 10;
        view.clipsToBounds = 1;
        view.layer.rasterizationScale = [UIScreen mainScreen].scale;
        view.layer.shouldRasterize = 1;
        view.backgroundColor = [UIColor blueColor];
        [cell.contentView addSubview:view];
    }
    return cell;
}

结果:

在这个 clipsToBound 里面是 Bool 所以你应该给出 YES 或 NO 并尝试使用 maskToBound = YES 作为角半径如果你想合并下面的视图比相应地使用 clipsToBound 我不认为 rasterizationScale 和 shouldRasterize在这里有用。希望对您有所帮助。

  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * settCellID = @"settingCellID";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:settCellID];
if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:settCellID];

    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(100, 10, 20, 20)];
    view.layer.cornerRadius = 10;
    view.clipsToBounds = YES;
    view.maskToBounds =YES;
    view.layer.rasterizationScale = [UIScreen mainScreen].scale;
    view.layer.shouldRasterize = 1;
    view.backgroundColor = [UIColor blueColor];
    [cell.contentView addSubview:view];
}
return cell;
}

如果你想要 UITableViewCell 圆角和裁剪子视图而不是按照这个 Link Click here

rasterizationScale 和 shouldRasterize 是针对"Off-Screen Rendering"的,但对圆形视图没有影响。 "view.clipsToBounds = YES" 等于 "view.layer.masksToBounds = 1"。我已经使用 CGContextRef 和 UIBezierPath 在 UITableViewCell 上创建了一个圆形视图,但是它们不能创建一个真正的圆形视图。

您将尝试创建一个自定义单元格 Class,并创建您的视图,而不是使用故事板以编程方式创建它。并在自定义单元格 class 中设置视图 属性。然后实现上面的代码,但我在这里提到了一点点变化。

static NSString * settCellID = @"settingCellID";
'CustomClassName' * cell = (CustomClassName*)[tableView dequeueReusableCellWithIdentifier:settCellID];
cell.viewPropertyName.layer.cornerRadius = 10;
cell.viewPropertyName.clipsToBounds = YES;
cell.viewPropertyName.maskToBounds =YES;
cell.viewPropertyName.backgroundColor = [UIColor blueColor];