[英]Collection view shows cells as selected at scrolling that haven't been selected
在我的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)根据数组中对象中的值设置值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.