swift4 代理的写法

简单记录swift中的代理的写法。首先在storyboard中画出两个VC:


swift4 代理的写法_第1张图片
image.png

然后,把对应的类文件添加上

//
//  ViewController.swift
//  DelegateTest
//
//  Created by iOS on 2018/2/27.
//  Copyright © 2018年 iOS. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var showTextLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }

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

    @IBAction func nextAction(_ sender: UIButton) {
        let vc = NextViewController.instance()
        vc.delegate = self
        present(vc, animated: true) {}
    }
    
}

extension ViewController: NextViewControllerProtocol {
    func callBack(string: String) {
        showTextLabel.text = string
    }
}
//
//  NextViewController.swift
//  DelegateTest
//
//  Created by iOS on 2018/2/27.
//  Copyright © 2018年 iOS. All rights reserved.
//

import UIKit

protocol NextViewControllerProtocol: NSObjectProtocol {
    func callBack(string: String)
}

class NextViewController: UIViewController {

    @IBOutlet weak var ContentStr: UILabel!
    weak var delegate:NextViewControllerProtocol?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    class func instance() -> NextViewController {
        let storeB = UIStoryboard.init(name: "Main", bundle: nil)
        let vc = storeB.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController
        return vc
    }
    
    @IBAction func back(_ sender: UIButton) {
        delegate?.callBack(string: ContentStr.text ?? "没有数据")
        dismiss(animated: true) {}
    }
}

实现效果是反向传值。

你可能感兴趣的:(swift4 代理的写法)