用協議在兩個界面傳遞數據

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

}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容