swift闭包逆向传值

2016-08-17  本文已影响44人  i得深刻方得S

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.

}

*/

}

上一篇下一篇

猜你喜欢

热点阅读