我有一个 UICollectionViewCell
带有元素 Desk
.办公 table 上有一个Bool
点击单元格时我想要更改的属性。
我正在尝试更好地熟悉委托(delegate)模式,并希望避免使用覆盖在单元格上的透明按钮之类的东西。我认为在 cellForItemAt
中分配单元格的委托(delegate)会起作用。并触发 didSelectItemAt
中的委托(delegate)方法,但是当我 checkin didSelectItemAt
时,单元格的委托(delegate)为零.
结构:
struct Desk: Equatable, Codable {
var name: String
var wasTouched: Bool = false
}
协议(protocol):
protocol TouchTheDesk: AnyObject {
func youTouchedIt(cell: DeskCell)
}
细胞:
import UIKit
class DeskCell: UICollectionViewCell {
@IBOutlet weak var deskLbl: UILabel!
weak var delegate: TouchTheDesk?
var desk: Desk? {
didSet {
updateViews()
}
}
func updateViews() {
self.deskLbl.text = desk?.name
}
}
使 VC 符合 Protocol 并定义委托(delegate)方法:
extension NotAShoppingListVC: TouchTheDesk {
func youTouchedIt(cell: DeskCell) {
if cell.desk?.wasTouched != nil {
cell.desk!.wasTouched = !cell.desk!.wasTouched
} else {
cell.desk!.wasTouched = true
}
collectionView.reloadData()
}
}
cellForItemAt:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? DeskCell else {return UICollectionViewCell()}
cell.desk = deskDealer.desks[indexPath.item]
if cell.desk!.wasTouched { //assigned on line above
cell.backgroundColor = .red
} else {
cell.backgroundColor = .green
}
cell.delegate = self
return cell
}
didSelectItemAt:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? DeskCell else {return}
#warning("delegate is nil")
cell.delegate?.youTouchedIt(cell: cell)
}
编辑:如果我直接在
didSelectItemAt
中调用委托(delegate)方法并传入单元格,在委托(delegate)方法中单元格的 indexPath 为 nil
最佳答案
内部 didSelectItemAt
代替
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? DeskCell else {return}
和
guard let cell = collectionView.cellForItem(at: indexPath) as? DeskCell else {return}
当您使用
dequeueReusableCell
cellForItemAt
之外它将返回与单击的单元格不同的单元格
关于ios - 在 didSelectItemAt 中,单元格的委托(delegate)为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436789/