假设您在UICollectionView的单元格(来自图像名称数组)中设置一堆图像视图,并在设置项目时默认设置为alpha 0.5。swift collectionview cell didSelectItemAtIndexPath如果滚动显示错误的单元格
然后,您在didSelectItemAtIndexPath func中将图像视图的alpha设置为1.0,所以当用户点击时它变为alpha 1。
这适用于用户点击单元格,但如果用户滚动,则该单元格不会保留,因为该单元格正被其他某个级别的UI重新使用。
结果是更远的另一个单元格(当滚动时)变为alpha 1.0,并且您选择的原始单元格恢复为以前的alpha 0.5外观。
我明白这一切都是为了让设备上的东西更加高效,但我还没有想出如何在选定项目持续存在的情况下正常工作。
ANSWER
苹果不对于您可以用它来改变背景颜色,阴影效果,或轮廓等,他们还允许您使用与细胞内的细胞图像提供selectedBackgroundView “默认”和“突出显示”状态。
这两种方法都会在选择正确的情况下持续存在。但是,如果您希望使用属性或不同于指定所选状态的属性或元素之一的元素,则必须使用包含对当前选定项目的引用的单独数据模型元素。然后,当用户选择一个项目时,您必须重新加载视图控制器数据,从而导致单元格全部重新绘制,并将选定状态应用于其中一个单元格。
下面是我用来解决我的问题的代码,谢谢马特的耐心和帮助。
所有这些都可以位于主UICollectionView控制器类文件中,或者如果需要在项目的其他地方使用它,数据数组和结构可以位于其自己的swift文件中。
数据和数据模型:
let imagesArray=["image1", "image2", "image3", ...]
struct Model {
var imageName : String
var selectedState : Bool
init(imageName : String, selectedState : Bool = false){
self.imageName = imageName
self.selectedState = selectedState
}
}
代码为UICollectionView控制器
// create an instance of the data model for images and their status
var model = [Model]()
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// build out a data model instance based on the images array
for i in 0..<imagesArray.count {
model.append(Model(imageName: imagesArray[i]))
// the initial selectedState for all items is false unless otherwise set
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesArray.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// when the collectionview is loaded or reloaded...
let cell:myCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! myCollectionViewCell
// populate cells inside the collectionview with images
cell.imageView.image = UIImage(named: model[indexPath.item].imageName)
// set the currently selected cell (if one exists) to show its indicator styling
if(model[indexPath.item].selectedState == true){
cell.imageView.alpha = 1.0
} else {
cell.imageView.alpha = 0.5
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// when a cell is tapped...
// reset all the selectedStates to false in the data model
for i in 0..<imagesArray.count {
model[i].selectedState = false
}
// set the selectedState for the tapped item to true in the data model
model[indexPath.item].selectedState = true
// refresh the collectionView (triggering cellForItemAtIndexPath above)
self.collectionView.reloadData()
}
Swift与它无关。语法与它无关。这只是一个认识到单元重用的问题,所以唯一稳定的就是数据模型。好的,我已经为你写出了一个完整的实例。 – matt
现在尝试一下,我会在我拥有它时报告。谢谢。 – dmcknight
如果您需要我通过电子邮件发送演示项目,请告诉我。 – matt