用协议在两个界面传递数据

ViewController

class ViewController: UIViewController, SecondViewControllerDelegate {
    @IBOutlet weak var titleLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    @IBAction func didClick(sender: UIButton) {
        //1. 创建第二个页面的对象
        let secondCtrl = SecondViewController()
        //耦合:松/紧
        secondCtrl.delegate = self
        //2. 显示
        self.presentViewController(secondCtrl, animated: true, completion: nil)
    }
    
    //通过函数参数从第二个页面返回数据
    func didTouched(data: String?) {
        print(data!)
    }
    
    //通过返回值给第二个页面传递数据
    func fetchData() -> String {
        return "yyyyy"
    }
}

SecondViewControllerDelegate

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

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

推荐阅读更多精彩内容