iOS 闭包传值 和 代理传值

时间:2023-03-09 16:02:53
iOS 闭包传值 和 代理传值

let vc = ViewController()

let navc = UINavigationController(rootViewController: vc)

window = UIWindow(frame: UIScreen.mainScreen().bounds)

window?.backgroundColor = UIColor.whiteColor()

window?.rootViewController = navc

window?.makeKeyAndVisible()

// Override point for customization after application launch.

return true

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

let btn = UIButton(frame: CGRectMake(50, 100, 60, 60))

btn.setTitle("下一页", forState: UIControlState.Normal)

btn.backgroundColor = UIColor.redColor()

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

view.addSubview(btn)

// Do any additional setup after loading the view, typically from a nib.

}

func pushToSecondVC(){

let secondVC = SecondViewController()

secondVC.closure = {

(color:UIColor)->Void

in

self.view.backgroundColor = color

}

navigationController?.pushViewController(secondVC, animated: true)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}

import UIKit

class SecondViewController: UIViewController {

var closure:((color:UIColor)->Void)?

override func viewDidLoad() {

view.backgroundColor = UIColor.cyanColor()

super.viewDidLoad()

let btn = UIButton(frame: CGRectMake(50, 100, 60, 60))

btn.setTitle("上一页", forState: UIControlState.Normal)

btn.backgroundColor = UIColor.redColor()

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

view.addSubview(btn)

// Do any additional setup after loading the view.

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

func popToFirstVC(){

let greenColor = UIColor.greenColor()

closure!(color:greenColor)

navigationController?.popViewControllerAnimated(true)

}

/*

// 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.

}

*/

}