gpt4 book ai didi

ios - Collection View 显示滚动时选择的尚未选择的单元格

转载 作者:行者123 更新时间:2023-11-30 13:53:22 24 4
gpt4 key购买 nike

在我的CollectionView中,我希望用户选择单元格。如果选择了一个单元格,则应出现图像并且标签应消失。用户还应该能够再次取消选择单元格,然后再次选择它(取消选择后的选择目前不起作用)。标签的文本来自数组并正确显示。但是当选择一个单元格,然后滚动其他单元格时就会被选中。当再次随机向上滚动时,将选择从未被触摸过的其他单元格。我认为它必须与单元格的重用有关,因此我已经在单元格的类中添加了一个 prepareForReuse 方法。

我还想存储用户关闭应用程序时选择的单元格,并在他再次打开应用程序时将它们显示为选中状态。

另一个问题是,我希望只能在选择某个其他单元格时才可以选择一个单元格。最好的方法是什么?

class CollectionViewController: UICollectionViewController {

var array:[String] = []

var selectedIndexes:NSMutableDictionary = NSMutableDictionary()

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

doors = ["1","2","3"]

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell:MyCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell

var Label = cell.viewWithTag(1) as! UILabel

Label.text = array[indexPath.row]

let keystring = String(format:"%i", indexPath.row)

if (self.selectedIndexes[keystring] != nil) {

cell.myLabel.hidden = true
cell.myImageView.image = UIImage(named:"1")!

}
else {

}

return cell
}

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

let keystring = String(format:"%i", indexPath.row)

if (self.selectedIndexes[keystring] != nil) {

let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell

cell.myLabel.hidden = false
cell.myImageView.image = nil

}
else {

selectedIndexes.setObject(keystring, forKey: keystring)

let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell

cell.myLabel.hidden = true
cell.myImageView.image = UIImage(named:"1")!


}

CollectionViewCell 的类:

class MyCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myImageView: UIImageView!

override func prepareForReuse() {
super.prepareForReuse()

self.myImageView.image = nil
self.myLabel.hidden = false

最佳答案

单元格被重用(这极大地优化了表格滚动速度等),正如您所描述的,这是您的“问题”。您所要做的就是在加载单元格时“重新初始化”文本和标签等。最好的办法是将单元格内容放在一个对象中,并将这些对象放在一个数组中。当我加载单元格时,您可以使用 cellForRowAtIndexPath (在默认实现中通常为 indexPath.row)根据数组中对象的值设置值

关于ios - Collection View 显示滚动时选择的尚未选择的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33975076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com