Swift闭包传值

一 、AppDelegate.swift 里设置导航控制器

import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

// Override point for customization after application launch.

//  设置导航控制器

let vc = ViewController()

window?.rootViewController = UINavigationController(rootViewController: vc)

return true

}

二 、第一个界面 设置按钮和Lable属性

import UIKit

class ViewController: UIViewController {

//  懒加载按钮

lazy var btn:UIButton = {

//  设置按钮的大小

let btn = UIButton(frame: CGRectMake(150, 350, 50, 50))

//  设置按钮的背景颜色

btn.backgroundColor = UIColor.redColor()

//  设置按钮的标题

btn .setTitle("First", forState: UIControlState.Normal)

//  给按钮的添加点击事件

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

return btn

}()

//  按钮点击事件的方法

func btnAction(btn:UIButton)->(){

let secVC = SecondViewController()

//  闭包传值

secVC.closure = {

(str:String)->()

in

self.lab.text = str

}

navigationController?.pushViewController(secVC, animated: true)

}

//  懒加载UILable

lazy var lab:UILabel = {

//  设置lab的大小

let lab = UILabel(frame: CGRectMake(80, 150, 200, 30))

lab.backgroundColor = UIColor.magentaColor()

//  设置lab的背景颜色

return lab

}()

override func viewDidLoad() {

super.viewDidLoad()

self.title = "闭包传值"

//  改变父视图背景颜色

view.backgroundColor = UIColor.whiteColor()

//  将按钮添加到父视图

view.addSubview(btn)

//  将lab添加到父视图

view.addSubview(lab)

}

}


二 、第二个界面 设置按钮和UITextFiled属性

import UIKit

class SecondViewController: UIViewController {

//  创建闭包

var closure:((str:String)->())?

//  懒加载按钮

lazy var btn:UIButton = {

//  设置按钮的大小

let btn = UIButton(frame: CGRectMake(150, 350, 80, 50))

//  设置按钮的背景颜色

btn.backgroundColor = UIColor.blueColor()

//  设置按钮的标题

btn .setTitle("Second", forState: UIControlState.Normal)

//  给按钮的添加点击事件

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

return btn

}()

//  实现懒加载的点击事件方法

func btnAction(btn:UIButton)->(){

//  执行闭包

closure!(str:textField.text!)

navigationController?.popToRootViewControllerAnimated(true)

}

//  懒加载UITextField

lazy var textField:UITextField = {

let textField = UITextField(frame: CGRectMake(80, 150, 200, 30))

textField.backgroundColor = UIColor.greenColor()

return textField

}()

override func viewDidLoad() {

super.viewDidLoad()

view.backgroundColor = UIColor.cyanColor()

view.addSubview(textField)

view.addSubview(btn)

}

你可能感兴趣的:(Swift闭包传值)