gpt4 book ai didi

ios - 如何更改已点击的 UICollectionViewCell 的背景图像?

转载 作者:搜寻专家 更新时间:2023-11-01 06:22:48 25 4
gpt4 key购买 nike

我有多个 UICollectionViewCells。当用户点击特定单元格时,我希望我的应用程序更改被触摸单元格的背景图像。

我的方法是专注于 didSelectItemAtIndexPath 方法。当一个单元格被触摸时,这个方法将被调用。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var cell: UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cellIdentifier", forIndexPath: indexPath) as! UICollectionViewCell
cell.backgroundView = UIImageView(image: UIImage(named: "myImage"))
}

但是,我无法让它工作,但我不知道为什么。该问题可能与 indexPath 有关,它没有返回正确的单元格值。我尝试使用 indexPath.row,这实际上返回了单元格的 Int 编号。

此外,我还使用 var 创建了一个新的 UICollectionViewCell,但该单元格已经存在。

为什么单元格不更新其背景图像?如何更改已被用户触摸的 UICollectionViewCell 的背景图像?

最佳答案

我完全同意 Josh 的回答,但如果您使用 didSelectItemAtIndexPath 方法更改背景图像,它也能正常工作。然后,您可以使用返回指定 indexPath 处的 UITableViewCellcellForRowAtIndexPath 方法,如下所示:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {        
var cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!
cell.backgroundView = UIImageView(image: UIImage(named: "photo2"))
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.backgroundView = UIImageView(image: UIImage(named: "photo1"))
cell.selectionStyle = .None
return cell
}

我只是将 selectionStyle 设置为 .None 以避免突出显示。希望对您有所帮助。

关于ios - 如何更改已点击的 UICollectionViewCell 的背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30405568/

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