ios - Swift - 想要在单击集合视图单元格内的按钮时进行更改
问题描述
我创建了一个包含 UIView 的集合视图单元格,并且在 UIView 内部有一个按钮。我想要做的是当按钮点击它会改变 UIView 边框颜色。我从服务器加载数据并将其显示到集合视图。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CypherCollectionViewCell", for: indexPath as IndexPath) as! CypherCollectionViewCell
cell.tickButton.addTarget(self, action: #selector(tickButtonClicked(sender:)), for: .touchUpInside)
return cell
}
@objc func tickButtonClicked( sender: UIButton) {
if sender.isSelected {
sender.isSelected = false
// To change the UIView border color
} else {
sender.isSelected = true
// To change the UIView border color
}
}
谢谢 !
解决方案
您可以将按钮点转换为视点并获得所需的单元格。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CypherCollectionViewCell", for: indexPath as IndexPath) as! CypherCollectionViewCell
cell.tickButton.addTarget(self, action: #selector(tickButtonClicked(sender:)), for: .touchUpInside)
return cell
}
@objc func tickButtonClicked( sender: UIButton) {
var convertedPoint : CGPoint = sender.convert(CGPoint.zero, to: self. collectionView)
var indexPath = self. collectionView.indexPathForItemAtPoint(convertedPoint)
let cell = self. collectionView.cellForItemAtIndexPath(indexPath) as! CypherCollectionViewCell
if sender.isSelected {
sender.isSelected = false
// To change the UIView border color
cell.view.borderColor = UIColor.blue()
} else {
sender.isSelected = true
// To change the UIView border color
cell.view.borderColor = UIColor.red()
}
}
推荐阅读
- c++ - 由泛型函数设置的数组绑定
- python - Opencv级联分类而不是检测
- apache - Apache .htaccess proxpass 不采用内部重定向参数
- ios - Angular / Cordova / IOS:如何在应用重新启动时保留 PHPSESSID cookie(使用 withCredentials)
- r - Grep 的问题
- metadata - 网站上的分享按钮不适用于 LinkedIn,但适用于 Facebook 和 Twitter
- ios - GMSMapView 更新相机位置,以便在导航期间始终显示朝向顶部的方向
- c# - deletesubkeytree 不删除注册表文件夹
- php - 无法使用 LexikBundle 以编程方式签署 JWT 令牌
- mysql - 数据库连接断开