我有一个 Collection View ,它会自动将单元格逐一滚动到末尾。在最后一个单元格中,我有一个按钮可以重新开始并滚动到第一个单元格。现在一切正常,但在滚动到第一个单元格后,我在第 3、6、9 个单元格(基本上每 3 个单元格 1 次)上看到我的重新开始按钮(这是我的最后一个单元格)。这是我的代码:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return alpImageArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if (indexPath.item >= alpImageArray.count - 1){
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AlphabetCollectionViewCell
cell.startAgain.isHidden = false
cell.startAgain.addTarget(self, action: #selector(startAgainPressed), for: .touchUpInside)
cell.alpImage.isHidden = true
cell.startAgain.setTitle("Start again", for: .normal)
return cell
} else {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AlphabetCollectionViewCell
cell.alpImage.image = UIImage(named: alpImageArray[indexPath.row] + ".png")
return cell
}
}
func scrollToNextCell(){
let cellSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)
let contentOffset = myCollectionView.contentOffset
myCollectionView.scrollRectToVisible(CGRect(x: contentOffset.x + cellSize.width, y: contentOffset.y, width: cellSize.width, height: cellSize.height), animated: true)
}
func startTimer() {
_ = Timer.scheduledTimer(timeInterval: 0.5,
target: self,
selector: #selector(scrollToNextCell),
userInfo: nil,
repeats: true)
}
@IBAction func startAgainPressed(_ sender: UIButton) {
myCollectionView.resetScrollPositionToTop()
}
}
extension UIScrollView {
/// Sets content offset to the top.
func resetScrollPositionToTop() {
self.contentOffset = CGPoint(x: -contentInset.left, y: -contentInset.left)
}
}
最佳答案
您会看到 Start Again 按钮在最初出列后被重新使用。
由于您为开始按钮和 alpImage cases
使用了相同的 AlphabetCollectionViewCell
,因此最好将其出列一次。从那里,在 if 语句中按照您喜欢的方式配置单元格。试一试。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AlphabetCollectionViewCell
if (indexPath.item >= alpImageArray.count - 1) {
cell.alpImage.isHidden = true
cell.startAgain.isHidden = false
cell.startAgain.addTarget(self, action: #selector(startAgainPressed), for: .touchUpInside)
cell.startAgain.setTitle("Start again", for: .normal)
} else {
cell.startAgain.isHidden = true
cell.alpImage.isHidden = false
cell.alpImage.image = UIImage(named: alpImageArray[indexPath.row] + ".png")
}
return cell
}
关于ios - 滚动到第一项后的 CollectionView 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41170133/