swift閉包逆向傳值

import UIKit

class BBViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

//創建一個按鈕

let? btn = UIButton(type: UIButtonType.Custom) as UIButton

btn.frame = CGRectMake(30, 100, self.view.frame.size.width-60, 40)

btn.setTitle("跳轉到第二個控制器", forState: UIControlState.Normal)

btn.setTitleColor(UIColor.magentaColor(), forState: UIControlState.Normal)

btn.addTarget(self, action: "Click", forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(btn)

// Do any additional setup after loading the view.

}

func Click(){

let? BBTC = BBTViewController()

BBTC.bbchange = { (title:String,coloer:UIColor) in

self.title = title

self.view.backgroundColor = coloer

}

self.navigationController?.pushViewController(BBTC, animated: true)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

第二個控制器是:

//

//? BBTViewController.swift

//? Swift_009

//

//? Created by 周雙建 on 15/12/7.

//? Copyright ? 2015年 周雙建. All rights reserved.

//

import UIKit

class BBTViewController: UIViewController {

//定義一個閉包,帶有兩個參數

var bbchange :((title:String,coloer:UIColor)->Void)?

override func viewDidLoad() {

super.viewDidLoad()

self.view.backgroundColor = UIColor.greenColor()

//創建一個按鈕

let? btn = UIButton(type: UIButtonType.Custom) as UIButton

btn.frame = CGRectMake(30, 100, self.view.frame.size.width-60, 40)

btn.setTitle("返回到第1個控制器", forState: UIControlState.Normal)

btn.setTitleColor(UIColor.magentaColor(), forState: UIControlState.Normal)

btn.addTarget(self, action: "bClick", forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(btn)

// Do any additional setup after loading the view.

}

func bClick(){

bbchange?(title:"成龍",coloer:UIColor.redColor())

self.navigationController?.popToRootViewControllerAnimated(true)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

/*

// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

// Get the new view controller using segue.destinationViewController.

// Pass the selected object to the new view controller.

}

*/

}

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

推薦閱讀更多精彩內容