【问题标题】:Custom UITableViewCell shadow appears after scrolling滚动后出现自定义 UITableViewCell 阴影
【发布时间】:2023-06-30 12:36:01
【问题描述】:

我正在使用表格视图控制器中的自定义表格视图单元格在 iOS6 中制作应用程序。该单元是使用情节提要中的原型单元设计的。

在表格视图控制器中,我正在做三件事:

  1. 在tableView:willDisplayCell:forRowAtIndexPath:的单元格中添加一个简单的自定义动画:
  2. 给tableView中的单元格添加圆角效果:cellForRowAtIndexPath:
  3. 给tableView中的单元格添加阴影效果:cellForRowAtIndexPath:

问题在于,当表格视图加载时,最初出现的 3 个单元格正确呈现动画和圆角,但 没有阴影效果。但是,当我向下滚动时,出现的新单元格也有动画 + 圆角 + 阴影。

而且,现在当我向上滚动时,最初的 3 个单元格也有阴影效果。

几个小时的调试让我更加一无所知。有什么建议吗?

【问题讨论】:

    标签: ios uitableview quartz-core


    【解决方案1】:

    我解决了问题。 [cell layoutSubviews] 做我需要的一切:

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.imageView.layer.masksToBounds = NO;
        cell.imageView.layer.cornerRadius = 5.0f;
        [cell layoutSubviews];
    }
    
    cell.imageView.layer.shadowOpacity = 0.5f;
    cell.imageView.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:cell.imageView.bounds cornerRadius:5.0f].CGPath;
    cell.imageView.layer.shadowOffset = CGSizeMake(2.5f, 2.5f);
    cell.imageView.layer.shadowRadius = 2.5f;
    

    【讨论】:

      【解决方案2】:

      如果其他人有这个问题:

      在您的UITableViewCell 子类中,覆盖layoutSubviews,然后插入添加阴影的代码。最后确保 super.layoutSubviews() 被称为代码的最后一行。

          override func layoutSubviews() 
      
          configureShadow() // <-- insert shadow code here, or create a method
          super.layoutSubviews()
      }
      

      然后在您的视图控制器中实现willDisplayCell 委托方法,将单元格转换为您的单元格子类,并在主线程上调用cell.layoutSubviews

          func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
      
              let _cell = cell as! CustomCell // Replace CustomCell with your cell subclass 
      
               DispatchQueue.main.async {
                  _cell.layoutSubviews()
              }
      }
      

      【讨论】: