gpt4 book ai didi

ios - 如何提高其中包含多个堆栈 View 的表格的滚动速度?

转载 作者:行者123 更新时间:2023-11-28 12:25:27 27 4
gpt4 key购买 nike

我有一个 UITableView,其中有多个 UIStackView 作为项目。在那些 UIStackView 中,我添加了彩色方 block 作为 subview 。问题是,它严重减慢了垂直滚动。

如何提高滚动性能?

这是滚动的样子: https://gfycat.com/DentalContentIndigowingedparrot

这是源代码: https://github.com/Cook10/StackTableProblem

最佳答案

您错过了重用单元格的要点。您的代码:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyTableViewCell

addStacksToTableCell(cell.stack1)
addStacksToTableCell(cell.stack2)
addStacksToTableCell(cell.stack3)
addStacksToTableCell(cell.stack4)

return cell
}

每次向下滚动并显示一个新单元格时,您将删除其中的所有 View (400 个 View )并创建新 View (400 个 View ),从而触发昂贵的布局和重新呈现机制。

每次滚动时都会发生这种情况。

这完全违背了重用单元格的目的。这与每次都创建一个新单元格相同。

相反,只创建一次 View ,并且在重复使用单元格时,只更新内部 View 的颜色。不要仅仅为了改变颜色而重新创建 View 。

使用一些非常幼稚的改变:

添加到您的单元格:

var createdViews: Bool = false
var views1: [UIView] = []
var views2: [UIView] = []
var views3: [UIView] = []
var views4: [UIView] = []

然后将您的 Controller 方法替换为:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell

if !cell.createdViews {
cell.views1 = addStacksToTableCell(cell.stack1)
cell.views2 = addStacksToTableCell(cell.stack2)
cell.views3 = addStacksToTableCell(cell.stack3)
cell.views4 = addStacksToTableCell(cell.stack4)

cell.createdViews = true
} else {
// only update the views
cell.views1.forEach { $0.backgroundColor = UIColor.random() }
cell.views2.forEach { $0.backgroundColor = UIColor.random() }
cell.views3.forEach { $0.backgroundColor = UIColor.random() }
cell.views4.forEach { $0.backgroundColor = UIColor.random() }
}

return cell
}

func addStacksToTableCell(_ stack: UIStackView) -> [UIView] {

stack.removeAllArrangedSubviews()

var views: [UIView] = []

for i in 0..<ITEMS{
let image = UIImageView()
image.backgroundColor = UIColor.random()
stack.addArrangedSubview(image)

let width = NSLayoutConstraint(item: image, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)
let height = NSLayoutConstraint(item: image, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)

image.addConstraints([width,height])

views.append(image)
}

return views
}

关于ios - 如何提高其中包含多个堆栈 View 的表格的滚动速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547791/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com