我有一个 UITableView
,它在滚动时执行动画,基本上是一个粘性标题,但它调整 UIView
的高度约束。我在滚动时的 CPU 使用率非常高。有没有更好的方法来执行这个动画?
编辑:我没有在 cellForRow at 函数中执行任何可能导致此问题的操作。肯定是scrollViewDidScroll函数。
滚动:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y + tableViewContentInsets
if (lastPoint != nil) {
if (lastPoint! < offset) {
if (portfolioSummaryInitialHeight - offset < portfolioSummaryInitialHeight){
if (portfolioSummaryInitialHeight - offset > 0 ){
portfolioSummaryHeightConstraint.constant = portfolioSummaryInitialHeight - offset
} else {
portfolioSummaryHeightConstraint.constant = 0
}
}
} else {
if (portfolioSummaryInitialHeight - offset < portfolioSummaryInitialHeight){
if (portfolioSummaryInitialHeight - offset > 0 ){
portfolioSummaryHeightConstraint.constant = portfolioSummaryInitialHeight - offset
}
} else {
portfolioSummaryHeightConstraint.constant = portfolioSummaryInitialHeight
}
}
}
lastPoint = offset
}
其他变量:
var tableViewContentInsets: CGFloat = 80
var portfolioSummaryInitialHeight: CGFloat = 0 // equals portfolioSummaryInitialHeight at viewDidLoad
var lastPoint: CGFloat?
最佳答案
首先,我建议您检查是否在主线程上执行了任何其他繁重的操作,例如数据获取或类似的操作。我创建了一个带有简单表格 View 和标题的简单测试项目。这是调整标题大小的代码。根据 CPU 报告,它在高峰时使用了 8% 的 CPU。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var headerHeightConstr: NSLayoutConstraint! //header's height constraint
@IBOutlet weak var tableView: UITableView!
private var headerHeight: CGFloat = 128.0 ////header's height constraint initial value
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "reuseID") else {
return UITableViewCell(style: .default, reuseIdentifier: "reuseID")
}
return cell
}
}
extension ViewController: UITableViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y < 0 {
self.headerHeightConstr.constant += abs(scrollView.contentOffset.y)
} else if scrollView.contentOffset.y > 0 && self.headerHeightConstr.constant >= headerHeight {
self.headerHeightConstr.constant -= scrollView.contentOffset.y
if self.headerHeightConstr.constant < headerHeight {
self.headerHeightConstr.constant = headerHeight
}
}
}
}
这是一种有点幼稚的方法,但它有效,如果需要,我们会尝试回答您的问题。
关于ios - UITableView滚动执行动画CPU使用率高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57885018/