swift4 代理的写法

######A控制器
import UIKit

class ViewController: UIViewController,NextViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
       
        
        let btn = UIButton(frame: CGRect(x: 0, y: 100, width: 100, height: 100));
        btn.backgroundColor = UIColor.red;
        self.view.addSubview(btn)
        btn.addTarget(self, action:#selector(pushclick), for: UIControlEvents.touchUpInside)
          
    }
   
    @objc func pushclick() {
        
        let vc = NextViewController()
        vc.titlestring = "哈哈"
        vc.delegate = self;
        self.navigationController?.pushViewController(vc, animated: true)
        // 设置代理,遵守协议,实现协议方法
    }
    
    func change(title:String){
        
        self.view.backgroundColor = UIColor.purple
        self.title = "xuxuuxux"
    }
    
}
######B控制器
import UIKit
protocol NextViewControllerDelegate:NSObjectProtocol{
    
    func change(title:String)
}
class NextViewController: UIViewController {

    var titlestring: String?
    weak var delegate: NextViewControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()

      self.view.backgroundColor = UIColor.yellow
        self.title = titlestring
        
        
        let btn = UIButton(frame: CGRect(x: 0, y: 100, width: 100, height: 100));
        btn.backgroundColor = UIColor.red;
        self.view.addSubview(btn)
        btn.addTarget(self, action:#selector(popclick), for: UIControlEvents.touchUpInside)
        
        
        
    }
    
    @objc func popclick() {
        
        delegate?.change(title: "hahahahha");
        self.navigationController?.popViewController(animated: true)
        
    }


}
创建通知中心
设置监听方法
设置通知的名字
        NotificationCenter.default.addObserver(self, selector: #selector(test), name: NSNotification.Name(rawValue:"isTest"), object: nil)

实现通知监听方法
@objc func test(nofi : Notification){
        let str = nofi.userInfo!["post"]
        print(String(describing: str!) + "this notifi")
    }

点击发送通知进行
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        NotificationCenter.default.post(name: NSNotification.Name("isTest"), object: self, userInfo: ["post":"NewTest"])
    }

最后要记得移除通知
    deinit {
        /// 移除通知
        NotificationCenter.default.removeObserver(self)
    }

推荐阅读更多精彩内容