我正在使用在我的子类中UIStackView
进行布局。我正在使用 iOS SDK 9.2UILabels
UICollectionViewCell
如果我在将它们出列时不更新标签,则集合视图的滚动是平滑的text
。但是,如果我在将它们出列时更新text
它们,则滚动非常慢。
我做了一个非常小的演示来展示问题,在设备(而不是模拟器)上运行。您可以创建一个新的空项目并将其内容替换为ViewController.swift
:
import UIKit
class ViewController: UIViewController {
override func loadView() {
view = UIView()
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 100, height: 200)
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.registerClass(Cell.self, forCellWithReuseIdentifier: "Cell")
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.dataSource = self
view.addSubview(collectionView)
let constraints = ["H:|-[collectionView]-|",
"V:|[collectionView]|"
].flatMap { NSLayoutConstraint.constraintsWithVisualFormat($0, options: [], metrics: nil, views: ["collectionView": collectionView])
}
NSLayoutConstraint.activateConstraints(constraints)
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! Cell
//comment out the line below to make the scrolling smoother:
cell.fillLabels()
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
}
class Cell: UICollectionViewCell {
var labelArray = [UILabel]()
func fillLabels() {
for label in labelArray {
label.text = "\(label.text!) yo"
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = UIColor.whiteColor()
let stackView = UIStackView()
stackView.axis = .Horizontal
stackView.alignment = .Leading
stackView.distribution = .EqualSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(stackView)
let leftStack = UIStackView()
leftStack.axis = .Vertical
let rightStack = UIStackView()
rightStack.axis = .Vertical
stackView.addArrangedSubview(leftStack)
stackView.addArrangedSubview(rightStack)
for index in 0...10 {
let leftLabel = UILabel()
leftLabel.text = "\(index)"
leftStack.addArrangedSubview(leftLabel)
labelArray.append(leftLabel)
let rightLabel = UILabel()
rightLabel.text = "\(index)"
rightStack.addArrangedSubview(rightLabel)
labelArray.append(rightLabel)
}
let constraints = [
"H:|[stackView]|",
"V:|[stackView]|"
].flatMap {
NSLayoutConstraint.constraintsWithVisualFormat($0, options: [], metrics: nil, views: ["stackView": stackView])
}
NSLayoutConstraint.activateConstraints(constraints)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
当您注释掉对fillLabels
.
如果您尝试在没有UIStackViews
并包含 call的情况下重现相同的布局fillLabels
,您会注意到滚动也很流畅。
这表明UIStackView
如果重新计算其布局,则会遇到性能瓶颈。
这个假设正确吗?有一些解决方案吗?