您的位置:首页 > 移动开发 > Swift

Swift 闭包(Closures)传值

2016-04-18 17:26 429 查看
//

// ViewController.swift

// YlwDome

//

// Created by ylw on 16/2/18.

// Copyright © 2016年 Ylw. All rights reserved.

//

import UIKit

class ViewControllerOne: UIViewController {

var name:String = ""

//MARK: -生命周期
override func viewDidLoad() {
super.viewDidLoad()
let make = CGRectMake(40, 80, 30, 30)
let bt = UIButton(frame: make)
bt.backgroundColor = UIColor.blueColor()
bt.addTarget(self, action: #selector(ViewControllerOne.click), forControlEvents: .TouchUpInside)
self.view.addSubview(bt)
}

override func viewDidAppear(animated: Bool) {
print("\(name)")
}

deinit {
print("ViewControllerOne deinit")
}

//MARK: -私有方法
func click() {
let vcTwo = ViewControllerTwo()
vcTwo.backClick = {
[unowned self] (str:String) in
self.name = str
}
self.navigationController?.pushViewController(vcTwo, animated: true)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}


=========================================

//

// ViewControllerTwo.swift

// YlwDome

//

// Created by ylw on 16/2/18.

// Copyright © 2016年 Ylw. All rights reserved.

//

import UIKit

class ViewControllerTwo: UIViewController {

typealias backMethod = (String) -> Void
var backClick:backMethod?

//MARK: -生命周期
override func viewDidLoad() {
super.viewDidLoad()
let make = CGRectMake(40, 80, 30, 30)
let bt = UIButton(frame: make)
bt.backgroundColor = UIColor.redColor()
bt.addTarget(self, action: #selector(ViewControllerTwo.Click), forControlEvents: .TouchUpInside)
self.view.addSubview(bt)
}

deinit {
print("ViewControllerTwo deinit")
}

//MARK: -私有方法
//@objc 可加可不加  参考: http://stackoverflow.com/questions/30027322/how-to-call-private-class-function-from-selector-in-swift/34291667#34291667 
@objc private func Click() {
if backClick != nil {
backClick!("ylw")
}
self.navigationController!.popViewControllerAnimated(true)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Swift