如何从用户函数中获取对单元格的引用
How to get reference to the cell from user function
我创建了自定义单元格,其中包含 UILabel 和 Button。在我连接 UIButton 作为控制器中的操作之后。如果触摸 Button,它会按预期改变图像,但我想要的是,在触摸后也改变 UILabel 的背景颜色。如何获取对我的自定义单元格的引用。
@IBAction func selectCell(_ sender: UIButton) {
if sender.imageView?.image == UIImage(named: "do") {
sender.setImage(UIImage(named: "done"), for: .normal)
} else {
sender.setImage(UIImage(named: "do"), for: .normal)
}
}
为什么不使用委托系统?这将使您可以轻松获得对您的单元格的引用。
在你身上cell.swift
@objc protocol CellDelegate: class {
func buttonPressed(forCell cell: Cell)
}
然后在您的单元格 class 中:您需要有一个委托 属性、您的 IBAction 方法以及设置委托的方法:
class Cell {
fileprivate weak var delegate: CellDelegate? = nil
func setup(withDelegate delegate: CellDelegate) {
self.delegate = delegate
}
@IBAction func deleteButtonPressed(_ sender: Any) {
if sender.imageView?.image == UIImage(named: "do") {
sender.setImage(UIImage(named: "done"), for: .normal)
} else {
sender.setImage(UIImage(named: "do"), for: .normal)
}
delegate?.buttonPressed(forCell: self)
}
}
最后在您的 TableViewController 中:您需要在配置单元格期间将委托设置为 self,并实现委托方法:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = viewModel.cellIdentifier(for: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell
cell.setup(withDelegate: self)
return cell
}
extension: TableViewController: CellDelegate {
func buttonPressed(forCell cell: Cell) {
//Do what you want
}
}
这就是我通常为单元格设置操作的方式
我创建了自定义单元格,其中包含 UILabel 和 Button。在我连接 UIButton 作为控制器中的操作之后。如果触摸 Button,它会按预期改变图像,但我想要的是,在触摸后也改变 UILabel 的背景颜色。如何获取对我的自定义单元格的引用。
@IBAction func selectCell(_ sender: UIButton) {
if sender.imageView?.image == UIImage(named: "do") {
sender.setImage(UIImage(named: "done"), for: .normal)
} else {
sender.setImage(UIImage(named: "do"), for: .normal)
}
}
为什么不使用委托系统?这将使您可以轻松获得对您的单元格的引用。
在你身上cell.swift
@objc protocol CellDelegate: class {
func buttonPressed(forCell cell: Cell)
}
然后在您的单元格 class 中:您需要有一个委托 属性、您的 IBAction 方法以及设置委托的方法:
class Cell {
fileprivate weak var delegate: CellDelegate? = nil
func setup(withDelegate delegate: CellDelegate) {
self.delegate = delegate
}
@IBAction func deleteButtonPressed(_ sender: Any) {
if sender.imageView?.image == UIImage(named: "do") {
sender.setImage(UIImage(named: "done"), for: .normal)
} else {
sender.setImage(UIImage(named: "do"), for: .normal)
}
delegate?.buttonPressed(forCell: self)
}
}
最后在您的 TableViewController 中:您需要在配置单元格期间将委托设置为 self,并实现委托方法:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = viewModel.cellIdentifier(for: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell
cell.setup(withDelegate: self)
return cell
}
extension: TableViewController: CellDelegate {
func buttonPressed(forCell cell: Cell) {
//Do what you want
}
}
这就是我通常为单元格设置操作的方式