gpt4 book ai didi

ios - 滚动到一个 collectionView 到一个物种索引

转载 作者:行者123 更新时间:2023-11-29 00:39:30 27 4
gpt4 key购买 nike

我有一个带有许多单元格的collectionView,当我加载它时,我想选择一个特定的单元格,将其显示为选定状态,并将 Collection View 滚动到所选单元格的位置,而无需自己滚动。

我可以将单元格显示为选定状态,但滚动似乎无法通过提供的功能进行。

这是我的尝试。

class RepsCellView: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

lazy var repsValuesCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.black
collectionView.showsHorizontalScrollIndicator = false
collectionView.translatesAutoresizingMaskIntoConstraints = false

return collectionView
}()

override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}



required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

func setupViews() {

addSubview(repsValuesCollectionView)

//...
// Cell
let selectedIndex = IndexPath(item: 19, section: 0)
repsValuesCollectionView.selectItem(at: selectedIndex, animated: true, scrollPosition: [.centeredHorizontally, .centeredVertically])

}

// CollectionView DataSource Functions
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
return cell
}
}

提前致谢。

最佳答案

您使用什么 ViewController 事件方法来运行代码?

无论如何,我可以滚动它,将您的代码放入 ViewController 事件方法 viewDidAppear 方法中。

class CollectionViewController: UICollectionViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

let cellToSelect = IndexPath(item: 99, section: 0)

self.collectionView?.scrollToItem(at: cellToSelect, at: [.centeredHorizontally, .centeredVertically], animated: true)
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RepsCellView
cell.setupViews() // added this line
return cell
}
}

关于ios - 滚动到一个 collectionView 到一个物种索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851031/

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