【发布时间】:2015-11-28 18:45:14
【问题描述】:
在我的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
【问题讨论】:
标签: ios swift uicollectionviewcell collectionview