UITableViewCell:圆角和阴影

UITableViewCell:圆角和阴影,第1张

UITableViewCell:圆角和阴影

这个问题适时出现了!我实际上只是自己解决了同样的问题。

  1. 在单元格的“内容视图”中创建一个
    UIView
    (让我们称其为
    mainBackground
    )。这将包含您单元格的所有内容。放置它并在情节提要中应用必要的约束。
  2. 创建另一个
    UIView
    。这将是一个带有阴影的阴影(我们将其称为
    shadowLayer
    )。完全按照您的方式放置它
    mainBackground
    ,但是在它后面,并应用相同的约束。
  3. 现在,您应该能够如下设置圆角和阴影:
        cell.mainBackground.layer.cornerRadius = 8      cell.mainBackground.layer.masksToBounds = true    cell.shadowLayer.layer.masksToBounds = false    cell.shadowLayer.layer.shadowOffset = CGSizeMake(0, 0)    cell.shadowLayer.layer.shadowColor = UIColor.blackColor().CGColor    cell.shadowLayer.layer.shadowOpacity = 0.23    cell.shadowLayer.layer.shadowRadius = 4

但是,这里的问题是:为每个单个单元格计算阴影是一项缓慢的任务。当您滚动浏览表格时,您会注意到一些严重的延迟。解决此问题的最佳方法是

UIBezierPath
为阴影定义一个,然后对其进行栅格化。因此,您可能需要这样做:

    cell.shadowLayer.layer.shadowPath = UIBezierPath(roundedRect: cell.shadowLayer.bounds, byRoundingCorners: .AllCorners, cornerRadii: CGSize(width: 8, height: 8)).CGPath    cell.shadowLayer.layer.shouldRasterize = true    cell.shadowLayer.layer.rasterizationScale = UIScreen.mainScreen().scale

但这带来了一个新问题!的形状

UIBezierPath
取决于
shadowLayer
的边界,但是在
cellForRowAtIndexPath
调用时间之前边界没有正确设置。因此,您需要调整
shadowPath
基于
shadowLayer
的范围。做到这一点的最佳方法是将其子类
UIView
,并将属性观察器添加到bounds属性中。然后在中设置阴影的所有属性
didSet
。切记
shadowLayer
在情节提要中更改您的类以匹配新的子类。

class ShadowView: UIView {    override var bounds: CGRect {        didSet { setupShadow()        }    }    private func setupShadow() {        self.layer.cornerRadius = 8        self.layer.shadowOffset = CGSize(width: 0, height: 3)        self.layer.shadowRadius = 3        self.layer.shadowOpacity = 0.3        self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 8, height: 8)).cgPath        self.layer.shouldRasterize = true        self.layer.rasterizationScale = UIScreen.main.scale    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5620075.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存