簡體   English   中英

Swift CollectionView ReloadData 暫時改變順序

[英]Swift CollectionView ReloadData changes order for a moment

我有一個非常簡單的 CollectionView,它顯示了 4 個按鈕,每個按鈕都有海龜的名字。 當我單擊任何按鈕時,我想刷新我的 CollectionView,以防我的數組增加並添加了第 5 個名稱,然后該名稱應顯示為第 5 個按鈕。 這基本上有效,但是當我按下並釋放任何按鈕時,按鈕標題從最后到第一個顯示我的數組,然后切換回從第一個到最后一個。

有誰知道它為什么這樣做以及我如何阻止它?

我只想在每次按下按鈕時更新我的​​ CollectionView。 如果數組應該增加,比如說“Splinter”,我希望前四個按鈕上的按鈕標題保持不變,只添加第 5 個按鈕。

非常感謝您提前!

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"]
}

據我了解,您看到按鈕標簽在按下手勢時正在更改,您想擺脫它。

請試試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM