swift4 代理的写法

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


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) {}
    }
}

实现效果是反向传值。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,251评论 4 61
  • 周末的清晨,阳光微醺。闲坐在庭院中,篱笆墙边的枫枝上,悄然露出些许嫩芽儿。忽而惊觉:清寒的冬季已过,初春的媚眼明眸...
    兰儿Landy阅读 841评论 2 8
  • 最近在看电视剧《急诊科的故事》,故事中有个情节是有一位叫沈岩的患者,骑摩托车被肇事,肇事者却逃逸了,沈岩被送到医院...
    A低调阅读 415评论 3 3
  • 一、归纳主义科学观 归纳类的科学观,是一个发现事实,观察规律在进行总结,并把事实变成既定的理论。 这种理论架构可能...
    系统升级永久阅读 476评论 0 0