我有一個UIView內的UITableView,它是由通過下面的類定義的自定義細胞的滾動:Laggy的UITableView因爲CAShapeLayer(SWIFT 3)
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的Instruments窗格中,當我運行應用程序並滾動laggy UITableView時,FPS不會反映了滯後性,儘管我可以清楚地說出這是非常滯後的。實際上,面板中的任何組件(CPU,內存,能源影響等)都沒有明顯差異。
更新:
我試圖移動layoutProfilePics(with:)
功能爲CustomAddFriendTableViewCell
的prepareForReuse()
功能,我也試圖把layoutProfilePics(with:)
在其layoutSubviews()
功能,但他們都沒有改善的滾動。
你應該改變'tableview(_:cellForRowAt:)'中的內容。你的這種方法在創建單元格時是一個很好的候選者,而不是在出列時。 –
我試着將函數移動到自定義單元格的類的'layoutSubviews()'函數中,並嘗試將它移動到自定義單元格的類的'prepareForReuse()'函數,但都沒有改進tableivew的滾動性能。 – RPatel99
您是否確保只將這些圖層添加到每個單元格中?請記住,單元格可以重複使用,並且在第一次使用時添加到單元格中的任何圖層在重用時都會保留在那裏,除非您刪除它們。 –