选项1. 与 委托一起 处理 __
处理从单元的子视图触发的事件的正确方法是使用 委托 。
因此,您可以按照以下步骤操作:
1. 在类定义上方,使用自定义单元格中的单个实例方法编写一个协议:
protocol CustomCellDelegate { func cellButtonTapped(cell: CustomCell)}2. 在类定义中声明一个委托变量,并在委托上调用protocol方法:
var delegate: CustomCellDelegate?@IBAction func buttonTapped(sender: AnyObject) { delegate?.cellButtonTapped(self)}3. 遵循表视图所在的类中的CustomCellDelegate:
class ViewController: CustomCellDelegate
4. 设置您的单元格的代表
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomCell cell.delegate = self return cell}5. 在视图控制器类中实现所需的方法。
编辑: 首先定义一个空数组,然后像这样修改它:
private var selectedItems = [String]()func cellButtonTapped(cell: CustomCell) { let indexPath = self.tableView.indexPathForRowAtPoint(cell.center)! let selectedItem = items[indexPath.row] if let selectedItemIndex = find(selectedItems, selectedItem) { selectedItems.removeAtIndex(selectedItemIndex) } else { selectedItems.append(selectedItem) }}其中 items 是在我的视图控制器中定义的数组:
private let items = ["Dog", "Cat", "Elephant", "Fox", "Ant", "Dolphin", "Donkey", "Horse", "Frog", "Cow", "Goose", "Turtle", "Sheep"]
选项2. 使用 闭包 处理 __
我决定回来,向您展示另一种处理这类情况的方法。在这种情况下使用闭包将减少代码量,您将实现目标。
1. 在单元格类中声明一个闭包变量:
var tapped: ((CustomCell) -> Void)?
2. 调用按钮处理程序中的闭包。
@IBAction func buttonTapped(sender: AnyObject) { tapped?(self)}3. 在
tableView(_:cellForRowAtIndexPath:)包含视图控制器的类中:
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell cell.tapped = { [unowned self] (selectedCell) -> Void in let path = tableView.indexPathForRowAtPoint(selectedCell.center)! let selectedItem = self.items[path.row] println("the selected item is (selectedItem)")}


