代理小结 iOS

自己不能干的事雇佣别人去干

//  MyView.swift
//  view中方法测试
//
//  Created by Admin on 2018/1/6.
//  Copyright © 2018年 刘普昌. All rights reserved.
//  http://blog.csdn.net/feng2qing/article/details/50850773

import UIKit

protocol viewProtocol: NSObjectProtocol {
    
    /// 这个是老板自己办不了的事(告示)
    func textProtocolMethod()
}


/// 主动方(老板)     备注: 一个拿钱找人办 自己办不了的事 的人
class MyView: UIView {
    
    
    /// 这个是老板准备给雇佣者的钱,但是雇佣者一定得具有完成这个事的能力 (雇佣金)
    weak var delegate: viewProtocol?
    
    
    lazy var button: UIButton = {
        let button = UIButton()
        button.backgroundColor = .red
        button.frame = CGRect.init(x: 100, y: 100, width: 100, height: 100)
        button.addTarget(self, action: #selector(click), for: .touchUpInside)
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .blue
        self.addSubview(button)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func click() {
        print("aaa")
        
//        let controller = getParentContorller()
//        print(getParentContorller())
//        controller.needComeTrueWay()
        
        /// 要求拿钱的人什么时候干这个自己干不了的事(有钱能使鬼推磨)
        delegate?.textProtocolMethod()
        
    }
    
    
    /// 方法2: 代理
    
    
    /// 方法1: 使用响应链传递的方式来进行查找控制器指针
    ///    (局限性 只有在视图有视图层级关系时使用,在model 和 viewcontroller时不能使用)
    func getParentContorller() -> ViewController {
        var next: UIResponder? = self.next
        repeat {
            next = next?.next
            print(next?.isKind(of: ViewController.self))
        } while !(next?.isKind(of: ViewController.self) ?? false)
        if next != nil {
            return next! as! ViewController
        }
        
        return ViewController()
    }
    
    
    
}
//  ViewController.swift
//  view中方法测试
//
//  Created by Admin on 2018/1/6.
//  Copyright © 2018年 刘普昌. All rights reserved.
//

import UIKit


/// 这个是来应聘人,具有干事能力的人,他先接了告示  (手撕告示)
class ViewController: UIViewController,viewProtocol {
    
    /// 实现协议方法 (展现能力解决老板问题)
    func textProtocolMethod() {
        self.needComeTrueWay()
    }
  
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let viewa = MyView.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: 200))
        
        
        /// 受命
        viewa.delegate = self
        
        view.addSubview(viewa)
        
        
        
    }
    
    
    
    
    func needComeTrueWay() {
        
        print("验证完毕哈")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

你可能感兴趣的:(代理小结 iOS)