美文网首页
8.3 用协议protocol 委托页面销毁

8.3 用协议protocol 委托页面销毁

作者: jayck | 来源:发表于2016-09-05 19:09 被阅读16次

协议委托

protocol SecondViewControllerDelegate {

    func didTouched(data: String?)

    func fetchData() -> String

}

页面一中用present显示

import UIKit

class ViewController: UIViewController, SecondViewControllerDelegate {

    @IBOutlet weak var titleLabel: UILabel!

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
    }

    @IBAction func didClick(sender: UIButton) {

        //1. 创建第二个页面的对象

        let secondCtrl = SecondViewController()

        //耦合:松/紧        松点比较好
              //关联使用协议的对象和调用协议的对象,如下

        secondCtrl.delegate = self  //self代表了整个第一个ViewContronller 
        //把第二个文件赋值给当前这个类的对象,使他们联系起来

        //2. 显示

        self.presentViewController(secondCtrl, animated: true, completion: nil)

        //用present显示它
    }

    //通过函数参数从第二个页面返回数据

    func didTouched(data: String?) {
        print(data!)
    }

    //通过返回值给第二个页面传递数据

    func fetchData() -> String {

        return "yyyyy"

    }

}

页面二中就用dismiss让它销毁

import UIKit

protocol SecondViewControllerDelegate {

    func didTouched(data: String?)

    func fetchData() -> String

}

class SecondViewController: UIViewController {

    var delegate: SecondViewControllerDelegate!

    override func viewDidLoad() {

        super.viewDidLoad()

        
        if delegate != nil {

            let s = delegate.fetchData()

            print("第二个页面: ", s)

        }

        self.view.backgroundColor = UIColor.redColor()

    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        if delegate != nil {

            delegate.didTouched("xxxx")

        }

        self.dismissViewControllerAnimated(true, completion: nil)
        //用dismiss销毁
    }
}

相关文章

网友评论

      本文标题:8.3 用协议protocol 委托页面销毁

      本文链接:https://www.haomeiwen.com/subject/sigrettx.html