Swift一步步学习

swift中的代理使用

2018-08-21  本文已影响0人  coderhlt
import UIKit
//声明一个协议clcikDelegate,需要继承NSObjectProtocol 
protocol clcikDelegate:NSObjectProtocol {
 func click()
}

class myView: UIView {
    override init(frame: CGRect) {
        super.init(frame:frame)
        self.backgroundColor = UIColor.yellow
        let btn = UIButton()
        btn.backgroundColor = UIColor.red
        btn.frame=CGRect(x: 0, y: 10, width: 100, height: 40)
        btn.addTarget(self, action: #selector(jump), for: UIControlEvents.touchUpInside)
        self.addSubview(btn)
    }
    //02、声明一个代理属性,必须用weak修饰
    weak var delegate:clcikDelegate?
    
    @objc func jump() {
        //和oc不一样的是,Swift中如果简单的调用代理方法, 不用判断代理能否响应
        delegate?.click()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
     let myview = myView()
        //成为delegate
        myview.delegate=self
        myview.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        view.addSubview(myview)
    }
}
//遵守协议,实现代理方法
extension ViewController:clcikDelegate{
    func click() {
        print("传值")
    }
}
上一篇下一篇

猜你喜欢

热点阅读