简体   繁体   English

iOS无法更改cellforrowatindexpath中图像的角半径

[英]ios can't change corner radius for image in cellforrowatindexpath

I am trying to round the corners of an image in cellforrowatindexpath like so: 我正在尝试像这样在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;
}

However, this doesn't work. 但是,这不起作用。 What am I doing wrong? 我究竟做错了什么?

Try, right after you set your image, calling: 设置图像后立即尝试调用:

[cell layoutSubviews];

I don't think that this is the best way to do it, but it is a hack that will work. 我不认为这是最好的方法,但这是可行的技巧。 This has been tested. 这已经过测试。

EDIT (for clarity): 编辑(为清楚起见):

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

The imageView has a frame of (0,0,0,0) at this point. 此时,imageView的帧为(0,0,0,0)。 So cell.imageView.frame.size.width is 0. Therefore, your code sets the cornerRadius to 0 again, which is a no-op. 因此cell.imageView.frame.size.width为0。因此,您的代码再次将cornerRadius设置为0,这是无操作的。

you could hardcode the value for cornerRadius or you could sublass the table view cell and override -layoutSubviews 您可以对cornerRadius的值进行硬编码,也可以对表视图单元进行子处理并覆盖-layoutSubviews

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM