swift代理的使用方法

來源:互聯網
上載者:User
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遵守協議,設定代理,調用代理方法, 具體代碼就不寫了
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.