由于CAShapeLayer(Swift 3)而导致Laggy UITableView滚动

时间:2017-07-17 05:22:55

标签: swift uitableview cashapelayer

我在UIView中有一个UITableView,它由以下类定义的自定义单元组成:

class CustomAddFriendTableViewCell: UITableViewCell {
    @IBOutlet weak var UsernameLbl: UILabel! 
    @IBOutlet weak var ProfileImg: UIImageView!
    @IBOutlet weak var AddFriendBtn: UIButton!
}

在ViewController的tableview(_:cellForRowAt:)方法中,我调用以下函数来布局单元格的ProfileImg:

private func layoutProfilePics(with cell:CustomAddFriendTableViewCell) {
    //create gradient
    let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: cell.ProfileImg.frame.size)
    gradient.colors = [Colors.blueGreen.cgColor, Colors.yellow.cgColor]

    //create gradient mask
    let shape = CAShapeLayer()
    shape.lineWidth = 3
    shape.path = UIBezierPath(ovalIn: cell.ProfileImg.bounds).cgPath // commenting this out makes lag go away
    shape.strokeColor = UIColor.black.cgColor // commenting this out makes lag go away
    shape.fillColor = UIColor.clear.cgColor
    gradient.mask = shape

    cell.ProfileImg.layoutIfNeeded()
    cell.ProfileImg.clipsToBounds = true
    cell.ProfileImg.layer.masksToBounds = true
    cell.ProfileImg.layer.cornerRadius = cell.ProfileImg.bounds.size.width/2.0
    cell.ProfileImg.layer.addSublayer(gradient)

}

此代码会导致ProfileImg为圆形,并且边框为蓝绿色渐变。 在它们旁边带有注释的两行使得滚动非常平滑(意味着渐变不是导致滞后的原因),所以我假设渲染CAShapeLayer(特别是笔划)导致问题(因此问题标题)。我该怎么做才能提高tableview的滚动性能?

此外,我不确定这是否是XCode错误或者是否与我的问题有关,但是在Project Navigator的“工具”窗格中,当我运行应用程序并滚动滞后的UITableView时,FPS没有反映出来虽然我可以清楚地说它是非常迟钝的,但是滞后。事实上,窗格中的任何组件(CPU,内存,能源影响等)都没有明显的差异。

更新

我尝试将layoutProfilePics(with:)函数移到CustomAddFriendTableViewCell的{​​{1}}函数中,我也尝试将prepareForReuse()放在layoutProfilePics(with:)函数中,但它们都没有改进了滚动。

1 个答案:

答案 0 :(得分:1)

该代码意味着每个单元格被调用一次,为此,它不应该在tableView(_:cellForRowAt:)中调用。尝试将该代码移至awakeFromNib(),如果您为自定义单元格使用nib,请使用viewDidLoad()中的以下代码加载出口:

let addFriendCellNib = UINib(nibName: "CustomAddFriendTableViewCell", bundle: nil)
tableView.register(addFriendCellNib, forCellReuseIdentifier: "addFriendCell")

我希望这适合你。

相关问题