【问题标题】:How to change UITableViewCell Image to Circle in UITableView如何在 UITableView 中将 UITableViewCell 图像更改为圆形
【发布时间】:2014-06-14 13:38:41
【问题描述】:

我的代码大部分都可以工作。

  • 我遇到的问题是图像一开始是方形的,当我滚动表格或刷新表格时变为圆形。

我错过了什么?

这是我的代码:

    cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2.0;
    cell.imageView.layer.borderWidth = 3.0;
    cell.imageView.layer.borderColor = [UIColor colorWithRed:157.0/255.0 green:34.0/255.0 blue:53.0/255.0 alpha:1.0]
    .CGColor;
    cell.imageView.clipsToBounds = YES;

    NSDictionary *tweet = (self.results)[indexPath.row];
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
    
        NSString * imageString = [tweet valueForKeyPath:@"user.profile_image_url"];
        NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:imageString]];
        
        if (imageData != nil)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                cell.imageView.image = [UIImage imageWithData: imageData];

                [cell setNeedsLayout];
            });
        }
    });

EDIT ---- 代码在cellForRowAtIndexPath

  • 当我启动应用程序时,单元格图像是方形的。如果我pullToRefresh 更改为圆形,或者如果我开始滚动表格,它们将更改为圆形。

编辑两个

我看到的另一个问题是滚动时图像会发生变化。

如何防止这种情况发生?

【问题讨论】:

  • 你在哪里有这个代码?
  • 您发布的代码表明您希望图像视图是圆形的,对吗?那么问题是它们最初看起来并不圆?
  • 它在 cellForRowAtIndexPath 中。是的,我希望它们始终是圆形的,但是如果我刷新或滚动,它们会以方形开始并更新为圆形。
  • 这里的每一件事都取决于行高。因此,如果您的行高为 100,只需将 cell.imageView.layer.cornerRadius=50;这意味着总是 rowHeight/2。
  • 我遇到了同样的问题。有时UIImageView 是圆形,有时不是。但是我发现如果您的图像高度和宽度等于单元格的高度,它会起作用。

标签: ios objective-c uitableview uiimageview


【解决方案1】:

如果有人遇到这个问题,这里是解决方案

斯威夫特

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:ContactCellTableViewCell? = tableView.dequeueReusableCellWithIdentifier("contactCell", forIndexPath: indexPath) as? ContactCellTableViewCell



    var contact : ContactStruct
    image = searchResults[indexPath.row]
    let newImage = resizeImage(image, toTheSize: CGSizeMake(70, 70))
    var cellImageLayer: CALayer?  = cell?.imageView.layer
    cellImageLayer!.cornerRadius = 35
    cellImageLayer!.masksToBounds = true
    cell?.imageView.image = newImage


    return cell!
}

您可能会注意到 35 硬编码基本上是图像大小的一半,即此处的 70。 这是调整大小的功能:

func resizeImage(image:UIImage, toTheSize size:CGSize)->UIImage{


    var scale = CGFloat(max(size.width/image.size.width,
        size.height/image.size.height))
    var width:CGFloat  = image.size.width * scale
    var height:CGFloat = image.size.height * scale;

    var rr:CGRect = CGRectMake( 0, 0, width, height);

    UIGraphicsBeginImageContextWithOptions(size, false, 0);
    image.drawInRect(rr)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext();
    return newImage
}

注意:我使用的自定义单元格类如下:

import UIKit

class ContactCellTableViewCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var contactImage: UIImageView!
    @IBOutlet weak var phoneLabel: UILabel!




    override func awakeFromNib() {
        super.awakeFromNib()

    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

我确实花了一段时间才弄清楚这一点。最初滚动后图像会变圆,但现在使用此代码,您将从一开始就将圆角图像放在单元格内。 希望它对任何人都有帮助。

【讨论】:

    【解决方案2】:

    在覆盖中试试这个-

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        // image Width(84) / 2 = 42
                cell.CellImage.layer.cornerRadius = 42.0
                cell.CellImage.layer.masksToBounds = true
             //or   
    
            cell.CellImage.layer.cornerRadius = cell.CellImage.frame.width / 2
            cell.CellImage.clipsToBounds = true
    }
    

    【讨论】:

      【解决方案3】:

      很可能在第一次创建单元格时没有设置单元格的框架(以及 imageView 的框架)。因此,基于初始帧设置 imageView 层的cornerRadius 不起作用。最好的解决方案是实现tableView:willDisplayCell:forRowAtIndexPath:委托方法并在那里设置层:

      - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
          cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2.0;
      }
      

      【讨论】:

      • 当我实现这个时仍然以正方形开始
      • cell.imageViewcell.imageView.frame 得到什么?
      • cell.imageView: > 和 cell.imageView.frame: 0.000000
      • 当我刷新时:cell.imageView: > 和 cell.imageView.frame: 4294968343.000000
      • 您可以为还没有图像的新单元格设置一个虚拟图像。这应该初始化imageView 框架,以便cornerRadius 计算按预期工作。
      【解决方案4】:

      很简单..

      - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
      {
          cell.ImageView.layer.cornerRadius = 150.0f;
          cell.ImageView.layer.borderWidth = 2.0f;
          cell.ImageView.layer.borderColor = [UIColor blackColor].CGColor;
          cell.ImageView.clipsToBounds = YES;
      }
      

      更多信息请参考此链接:http://ios-blog.co.uk/tutorials/quick-tips/how-to-create-rounded-avatars-in-your-ios-application/

      【讨论】:

        【解决方案5】:

        创建一个自定义单元格,并添加一个图像视图(带有IBOutlet),根据需要调整大小和位置(在下面的示例中,出口是“iv”)。在awakeFromNib 方法中放置代码以使图像视图变为圆形(假设您的单元格是在笔尖或情节提要中创建的)。

        -(void)awakeFromNib {
            self.iv.layer.cornerRadius = self.iv.frame.size.width / 2.0;
            self.iv.layer.borderWidth = 3.0;
            self.iv.layer.borderColor = [UIColor colorWithRed:157.0/255.0 green:34.0/255.0 blue:53.0/255.0 alpha:1.0].CGColor;
            self.iv.clipsToBounds = YES;
        }
        

        【讨论】:

        • Cell 已经带有imageView 属性。到目前为止的问题是默认 imageView 的框架在它获取图像之前没有设置。
        • @rmaddy,是的,我知道单元格带有图像视图属性。它的工作方式与我在这里所做的一样,没有图像。此外,我通常不喜欢在表视图的委托/数据源中设置不依赖于 indexPath 的东西。我认为那些东西应该属于细胞,所以这就是我建议这种方法的原因。
        • 这很有效,但前提是您在情节提要中明确指定 imageView 的高度。
        【解决方案6】:

        我遇到了类似的问题,我的 UIImageView 最初是一个正方形,只有当它所在的 UITableViewCell 被突出显示或选中时才会显示为圆形。

        这是一个简单的修复:

        Swift 2.0

        imgView.layer.cornerRadius = imgView.frame.width / 2
        imgView.clipsToBounds = true
        

        这被放置在 awakeFromNib() 中,用于我的自定义 UITableViewCell

        这是假设 imgView 是通过这个自定义 UITableViewCell 中的故事板连接的 UIImageView 的名称。

        【讨论】:

          【解决方案7】:
          @interface MyCell : UITableViewCell
          @end
          
          @implementation MyCell
          
          - (void)awakeFromNib
          {
              [super awakeFromNib];
              self.imageView.layer.masksToBounds = YES;
              self.textLabel.font = [UIFont systemFontOfSize:17];
              self.textLabel.textColor = [UIColor darkTextColor];
          }
          
          // --- image view frame is empty rect inside tableView: willDisplayCell:
          // +++ set cornerRadius inside layoutSubviews works. 
          - (void)layoutSubviews
          {
              [super layoutSubviews];
          
              // layout image view
              CGRect vfr = self.frame;
              CGRect imgvr = self.imageView.frame;
              imgvr.origin.x = 16;
              imgvr.size.width = CGRectGetHeight(vfr);
              self.imageView.frame = imgvr;
          
              // update corner radius
              self.imageView.layer.cornerRadius = imgvr.size.width * 0.5f;
          
              // layout label
              CGRect lblr = self.textLabel.frame;
              lblr.origin.x = CGRectGetMaxX(imgvr) + 16;
              lblr.size.width = CGRectGetWidth(vfr) - CGRectGetMaxX(imgvr) - 32;
              self.textLabel.frame = lblr;
          }
          
          @end
          

          【讨论】:

            【解决方案8】:

            如果您的单元格是代码:

            func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
                    let myImageView = (cell as! MyCustomCell).myImageView
                    myImageView.layoutIfNeeded()
                    myImageView.layer.cornerRadius = myImageView.frame.width / 2.0
             }
            

            【讨论】:

              【解决方案9】:
              cell.imageView?.layer.cornerRadius = 22.0
              cell.imageView?.layer.masksToBounds = true
              

              【讨论】:

              • 请在您的回答中描述问题是什么,以及这个 sn-p 将如何解决它,以帮助其他人理解这个答案
              【解决方案10】:

              将图像视图设置为您设置图像的async 调用内的一个圆圈。

              dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
              dispatch_async(queue, ^{
              
                  NSString * imageString = [tweet valueForKeyPath:@"user.profile_image_url"];
                  NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:imageString]];
              
                  if (imageData != nil)
                  {
                      dispatch_async(dispatch_get_main_queue(), ^{
              
                          cell.imageView.image = [UIImage imageWithData: imageData];
              cell.imageView.layer.cornerRadius = cell.imageView.frame.size.width / 2.0;
              cell.imageView.layer.borderWidth = 3.0;
              cell.imageView.layer.borderColor = [UIColor colorWithRed:157.0/255.0 green:34.0/255.0 blue:53.0/255.0 alpha:1.0]
              .CGColor;
              cell.imageView.clipsToBounds = YES;
                          [cell setNeedsLayout];
                      });
                  }
              });
              

              【讨论】:

                【解决方案11】:

                这是UITableview Cell 中圆形图像的完美解决方案。 只需使用以下代码修改您的 UITableviewCell(自定义单元格)类。

                override func awakeFromNib() {
                    super.awakeFromNib()
                    imgEvent.layer.frame = (imgEvent.layer.frame).insetBy(dx: 0, dy: 0)
                    imgEvent.layer.borderColor = UIColor.gray.cgColor
                    imgEvent.layer.cornerRadius = (imgEvent.frame.height)/2
                    imgEvent.layer.masksToBounds = false
                    imgEvent.clipsToBounds = true
                    imgEvent.layer.borderWidth = 0.5
                    imgEvent.contentMode = UIViewContentMode.scaleAspectFill
                  }
                

                这也有助于解决滚动表格后图像循环的问题..(如果有)

                【讨论】:

                  猜你喜欢
                  • 2018-10-26
                  • 1970-01-01
                  • 2014-04-09
                  • 1970-01-01
                  • 2020-05-16
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-08-08
                  • 1970-01-01
                  相关资源
                  最近更新 更多