如何更改已点击的 UICollectionViewCell 的背景图像?
How do I change the background image of a UICollectionViewCell that has been tapped?
我有多个 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
有关,return 单元格的值不正确。我尝试使用 indexPath.row
,这实际上是 return 一个 Int
单元格的编号。
另外,我还用 var
创建了一个新的 UICollectionViewCell
,但是这个单元格已经存在了。
为什么单元格不更新其背景图像?如何更改已被用户触摸的 UICollectionViewCell
的背景图像?
我完全同意 Josh 的回答,但如果您使用 didSelectItemAtIndexPath
方法更改背景图片,它也能正常工作。然后,您可以使用 cellForRowAtIndexPath
方法在指定的 indexPath
处 returns UITableViewCell
,如下所示:
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
以避免突出显示。希望对你有帮助。
我有多个 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
有关,return 单元格的值不正确。我尝试使用 indexPath.row
,这实际上是 return 一个 Int
单元格的编号。
另外,我还用 var
创建了一个新的 UICollectionViewCell
,但是这个单元格已经存在了。
为什么单元格不更新其背景图像?如何更改已被用户触摸的 UICollectionViewCell
的背景图像?
我完全同意 Josh 的回答,但如果您使用 didSelectItemAtIndexPath
方法更改背景图片,它也能正常工作。然后,您可以使用 cellForRowAtIndexPath
方法在指定的 indexPath
处 returns UITableViewCell
,如下所示:
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
以避免突出显示。希望对你有帮助。