【问题标题】:ios can't change corner radius for image in cellforrowatindexpathios 无法更改 cellforrowatindexpath 中图像的角半径
【发布时间】:2014-06-30 05:00:32
【问题描述】:

我正在尝试像这样在 cellforrowatindexpath 中圆角图像:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyCell";
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSString *identifiers = _identifiers[indexPath.row];

    if([identifier isEqualToString:@"bronze"]){
        cell.imageView.image = [UIImage imageNamed:@"bronze.png"];
        cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2;
        cell.imageView.clipsToBounds = YES;
    }



    return cell;
}

但是,这不起作用。我做错了什么?

【问题讨论】:

  • 你的目标是什么?要在图像周围绘制轮廓(如果您使用 Michael 的设置borderWidth 和borderColor 的建议,您会感到很奇怪)或者您是否尝试裁剪掉图像的角落?
  • 我正在尝试裁剪掉角落并制作一个图像的圆圈。这适用于我的代码中的其他地方,只是不适用于 celforrow
  • 您是否在if 中设置了断点?你确定代码真的被执行了吗?角半径设置为哪个实际值?如果将NSLog(@"in bronze. radius=%.1f", (float)(cell.imageView.frame.size.width / 2)); 放入 if 中,会打印什么?
  • 你的问题和 Cocoa 有什么关系?
  • @ElTomato 是的,应该是 cocoa-touch...

标签: ios objective-c uitableview cocoa-touch uiimageview


【解决方案1】:

尝试,在您设置图像后立即调用:

[cell layoutSubviews];

我认为这不是最好的方法,但它是一种可行的方法。 这已经过测试。

编辑(为清楚起见):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MyCell";
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSString *identifiers = _identifiers[indexPath.row];

    if([identifier isEqualToString:@"bronze"]){
        cell.imageView.image = [UIImage imageNamed:@"bronze.png"];
        [cell layoutSubviews];
        cell.imageView.layer.cornerRadius = CGRectGetWidth(cell.imageView.frame) / 2;
        cell.imageView.clipsToBounds = YES;
    } else {
        cell.imageView.image = nil;
        cell.imageView.layer.cornerRadius = 0;
    }

    return cell;
}

【讨论】:

  • 防守和突兀多?我现在应该开始向全能的迈克尔鞠躬吗?你应该考虑在门口检查你的自我。你的答案可能是正确的,我的可能是不正确的,但不需要像你刚才那样评论。坦率地说,OP可能不想要边界。圆角不需要边框。
  • 试过了,不起作用...因为:如果框架仍然是CGRectZero-layoutSubviews 是无操作的
  • 实际上,@Michael,您可能想再次检查框架。如果您在设置图像后调用 layoutSubviews,则现在已设置框架。您还必须检查以确保您的 cellStyle 也设置为 UITableViewCellStyleDefault,否则图像视图将为零。
【解决方案2】:

此时 imageView 的 frame 为 (0,0,0,0)。所以cell.imageView.frame.size.width 为0。因此,您的代码再次将cornerRadius 设置为0,这是一个无操作。

您可以硬编码cornerRadius 的值,或者您可以对表格视图单元进行分类并覆盖-layoutSubviews

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2023-04-01
    • 2019-01-04
    相关资源
    最近更新 更多