美文网首页
用协议在两个界面传递数据

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

作者: Dove_Q | 来源:发表于2016-10-12 12:44 被阅读10次

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

}

相关文章

网友评论

      本文标题:用协议在两个界面传递数据

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