swift创建代理

来源:互联网 发布:主机与设备传送数据时 编辑:程序博客网 时间:2024/05/17 23:44

最近稍微写了下swift,顺便努力的写了个代理的传值,贴出代码大家参考一下,最简单的方法写代理


基本流程是第二个页面的代理在第一个页面实现

第一个controller

import UIKit

class ViewController: UIViewController ,swiftDelegate{ //这里不要忘记引用代理

    override func viewDidLoad() {

        super.viewDidLoad()

let button =UIButton(frame: buttonrect)

        button.backgroundColor = UIColor.redColor()

        button.layer.cornerRadius =5

        button.setTitle("button", forState:UIControlState.Normal)

        button.addTarget(self, action:"buttonClick", forControlEvents: UIControlEvents.TouchUpInside)

        self.view.addSubview(button)

    }

    func buttonClick(){ //button的跳转方法

        print("aa")

        let secondController = second()

        secondController.delegate = self

        self.navigationController!.pushViewController(secondController, animated:true)

        

    }

    

    func changeValue(controller: second, string: String) {//代理方法实现

        print("\(string)")

    }

创建第二个controller

import UIKit


protocol swiftDelegate:NSObjectProtocol{

    func changeValue(controller:second,string:String)

    

}

class second: UIViewController {

    var delegate:swiftDelegate?

    override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor =UIColor.whiteColor()

        // Do any additional setup after loading the view.

        let rect = CGRect(x: 100, y: 100, width: 100, height: 30)

        let mybutton = UIButton(frame: rect)

        mybutton .addTarget(self, action:"myButtonClick", forControlEvents: UIControlEvents.TouchUpInside)

        mybutton.backgroundColor = UIColor.redColor()

        self.view.addSubview(mybutton)

    }

    func myButtonClick(){

        print("点击")

        if ((delegate) !=nil){

            delegate?.changeValue(self, string:"传值" )

        }

    }


如果文档有疑问也可以下载demo  https://github.com/yongchangye/demo 




0 0
原创粉丝点击