[英]Swift CollectionView ReloadData changes order for a moment
I have a very simple CollectionView which shows 4 buttons, each with the name of the Turtles.我有一个非常简单的 CollectionView,它显示了 4 个按钮,每个按钮都有海龟的名字。 When I click any button, I want to refresh my CollectionView in case my array has increased and a 5th name was added, which should then appear as a 5th button.当我单击任何按钮时,我想刷新我的 CollectionView,以防我的数组增加并添加了第 5 个名称,然后该名称应显示为第 5 个按钮。 This basically works, but the moment I press and release any button, the button titles show my array from the last to first and then switch back to first to last.这基本上有效,但是当我按下并释放任何按钮时,按钮标题从最后到第一个显示我的数组,然后切换回从第一个到最后一个。
Does anyone know why it does that and how I can stop it?有谁知道它为什么这样做以及我如何阻止它?
I just want to update my CollectionView every time a button was pressed.我只想在每次按下按钮时更新我的 CollectionView。 If the array should increase, let's say "Splinter", I want the Button titles to stay the same on the first four buttons and just a 5th button to be added.如果数组应该增加,比如说“Splinter”,我希望前四个按钮上的按钮标题保持不变,只添加第 5 个按钮。
Thank you very much in advance!非常感谢您提前!
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var meineCV: UICollectionView!
let cv = CollectionViewCell()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cv.turtles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.meinButton.setTitle(cv.turtles[indexPath.row], for: .normal)
cell.meinButton.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
return cell
}
@IBAction func buttonAction(_ sender: UIButton) {
print(sender.currentTitle!)
meineCV.reloadData()
}
}
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var meinButton: UIButton!
let turtles: [String] = ["Leonardo", "Donatello", "Michelangelo", "Raphael"]
}
As I understood you see that the button labels are being changed at the moment of press gestures and you want to get rid of it.据我了解,您看到按钮标签在按下手势时正在更改,您想摆脱它。
Please try this:请试试这个:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
let turtle = cv.turtles[indexPath.row]
cell.meinButton.titleLabel?.text = turtle
cell.meinButton.setTitle(turtle, for: .normal)
cell.meinButton.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
return cell
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.