简体   繁体   中英

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. 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. 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. 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM