swfie delegate传值

首先创建两个控制器每个控制器上各有一个button

其次再第二个控制器中声明delegate

@objcprotocol ViewcontrollerDelegate: NSObjectProtocol{

    @objc optionalfunc mainFun(string: NSString)

在第二个控制器中}

  var delegate :TwoDelegate?

第二个控制器的代码如下

import UIKit

@objcprotocol TwoDelegate:NSObjectProtocol{

    func getmessage(string:NSString)

}


class TwoViewController:UIViewController,ViewcontrollerDelegate {

    var delegate : TwoDelegate?

    

    

    @IBAction func buttonclick(_ sender:UIButton) {

        delegate?.getmessage(string:"789")

//        dismiss(animated: true, completion: nil)

        self.navigationController?.popViewController(animated:true)

    }

 

    override func viewDidLoad() {

        super.viewDidLoad()

        view.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)

       delegate?.getmessage(string:"caosiyuan")

        

        let button = UIButton(frame:CGRect(x: 300, y:300, width: 100, height:100))

        button.addTarget(self, action:#selector(back), for: .touchUpInside)

        button.setTitle("fanhui", for: .normal)

        view.addSubview(button)

        

    }

    func back() {

        delegate?.getmessage(string:"numhbbi")

        self.navigationController?.popViewController(animated:true)

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    



}




第一个控制器代码如下



//

//  ViewController.swift

//  delegateProtocol

//

//  Created by iApps on 17/2/15.

//  Copyright © 2017 iApps. All rights reserved.

//


import UIKit

@objc protocol ViewcontrollerDelegate:NSObjectProtocol{

    @objcoptional func mainFun(string:NSString)

}


class TestClass {

    weakvar delegate: ViewcontrollerDelegate?

}

class ViewController: UIViewController,ViewcontrollerDelegate,TwoDelegate {

var testInstance: TestClass!

    overridefunc viewDidLoad() {

        super.viewDidLoad()

        

        testInstance =TestClass()

        testInstance.delegate =self

        testInstance.delegate?.mainFun!(string:"123456")

       

    }


    overridefunc didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    func mainFun(string:NSString) {

        print(string)

    }

    func getmessage(string:NSString) {

        print(string)

    }

    

    @IBActionfunc two(_ sender:UIButton) {

        let twovc =TwoViewController()

        twovc.delegate =self

        self.navigationController?.pushViewController(twovc, animated:true)

    }

    

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值