import UIKit@objc protocol TestCellDelegate : class { //非必須實現 @objc optional func cellTestButtonClick(index: NSInteger) //在viewController必須實現, 不然會報錯 func buttonClick()}class TestCell: UITableViewCell { var delegate: TestCellDelegate? var testButton = UIButton() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.testButton = UIButton.init(type: UIButtonType.custom) self.testButton.frame = CGRect(x: 10, y: 10, width: 80, height: 40) self.testButton.setImage(UIImage.init(name: ""), for: UIControlState.normal) self.testButton.addTarget(self, action:#selector(testButtonClick), for: UIControlEvents.touchUpInside) self.addSubview(self.testButton) } var model : S_CollectDataModel? { didSet { } } func testButtonClick(button: UIButton) { if (self.delegate != nil) { self.delegate?.cellTestButtonClick!(index: self.tag) } }}
在viewController遵守協議,設定代理,調用代理方法, 具體代碼就不寫了