1.首先创建一个单例文件,继承NSObject类
import UIKit
class SwiftSingleton: NSObject {
// 单例颜色属性
var color = UIColor.orangeColor()
//这个位置使用static,static修饰的变量会懒加载
internal static let instance = SwiftSingleton()
private override init()
{
print("----");
}
}
2.在控制器里加入一个button
let btn = UIButton(frame:CGRectMake(view.frame.size.width/2-50,100,100,40))
btn.backgroundColor = UIColor.brownColor()
btn.addTarget(self, action: #selector(ViewController.btnClicked), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btw)
func btnClicked(){
let sec = SecViewController()
self.navigationController?.pushViewController(sec, animated: true)
}
3.创建第二个控制器
在第二个控制器里创建单例,给单例的属性赋值
self.view.backgroundColor = UIColor.whiteColor()
let R = Float(arc4random()%255)/255.0
let G = Float(arc4random()%255)/255.0
let B = Float(arc4random()%255)/255.0
let color = UIColor.init(colorLiteralRed: R, green: G, blue: B, alpha: 1.0)
// 单例赋值
let single = SwiftSingleton.instance
single.color = color
4.在第一个控制器加入一个方法viewWillAppear
// 单例取值
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
let single = SwiftSingleton.instance
self.view.backgroundColor = single.color
}
实现单例的反向传值
网友评论