繁体   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