Swift iOS:KVO

栏目: Swift · 发布时间: 6年前

内容简介:Swift iOS:KVO

KVO是Key Value Observer的缩写,可以用于监视一个对象的属性值变化,然后执行一个代码块(块、函数、闭包等)。Facebook开源了一个KVO框架,KVOController。

这个案例使用KVOController,用于App主题改变通知。通过KVO监视主题的值,当设置主题变化时,通知所有的UI类的主题处理器。代码如下:

import UIKit
import KVOController
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow();
        self.window?.frame=UIScreen.main.bounds;
        self.window?.makeKeyAndVisible();
        self.window?.rootViewController = Page()
        return true
    }
}
class Page: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let button   = UIButton(type: .system)
        button.frame = CGRect(x: 120, y: 150, width: 220, height: 50)
        button.contentHorizontalAlignment = .left
        button.setTitle("Peace",for: .normal)
        button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)
        view.addSubview(button)
        let button1   = UIButton(type: .system)
        button1.frame = CGRect(x: 120, y: 200, width: 220, height: 50)
        button1.contentHorizontalAlignment = .left
        button1.setTitle("Blood",for: .normal)
        button1.addTarget(self, action: #selector(buttonAction1(_:)), for: .touchUpInside)
        view.addSubview(button1)
        self.themeChangedHandler = {[weak self] (style) -> Void in
            if "Peace" == style{
                self!.view.backgroundColor = .blue
            }
            else{
                self!.view.backgroundColor = .red
            }
        }
    }
    func buttonAction(_ sender:UIButton!){
        ThemeColor.shared.style = "Peace"
    }
    func buttonAction1(_ sender:UIButton!){
        ThemeColor.shared.style = "Blood"
    }
}
class ThemeColor :NSObject  {
    dynamic var style:String
    static let shared = ThemeColor()
    fileprivate override init(){
        style = "Blood"// or Peace
        super.init()
    }
}
extension NSObject {
    fileprivate struct AssociatedKeys {
        static var themeChanged = "themeChanged"
    }
    public typealias ThemeChangedClosure = @convention(block) (_ style:String) -> Void
    var themeChangedHandler:ThemeChangedClosure? {
        get {
            let closureObject: AnyObject? = objc_getAssociatedObject(self, &AssociatedKeys.themeChanged) as AnyObject?
            guard closureObject != nil else{
                return nil
            }
            let closure = unsafeBitCast(closureObject, to: ThemeChangedClosure.self)
            return closure
        }
        set{
            guard let value = newValue else{
                return
            }
            let dealObject: AnyObject = unsafeBitCast(value, to: AnyObject.self)
            objc_setAssociatedObject(self, &AssociatedKeys.themeChanged,dealObject,objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            self.kvoController.observe(ThemeColor.shared, keyPath: "style", options: [.initial,.new] , block: {[weak self] (nav, color, change) -> Void in
                self?.themeChangedHandler?(ThemeColor.shared.style)
                }
            )
        }
    }
}

代码运行后,可以看到两个按钮,点击不同的按钮会切换主题。

Pod文件为:

pod 'KVOController', '~> 1.2.0'

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

实用程序育儿法

实用程序育儿法

(美)特蕾西·霍格、(美)梅林达·布劳 / 张雪兰 / 北京联合出版社 / 2009-1 / 39.00元

《实用程序育儿法》作者世界闻名的实战型育儿专家特蕾西·霍格(Tracy Hogg)以“宝宝耳语专家(Baby Whisperer)”享誉全球,她深入到数千名宝宝的家里解决宝宝和妈妈面临的日常难题,通过演讲、电台、电视台、信件、电子邮件以及住她的网站上发帖跟她交流、向她请教的妈妈们更是不计其数。由她亲自实景示范拍摄的“和宝宝说悄悄话(Thc Baby Whisperer)”DVD全球发行上千万张。她......一起来看看 《实用程序育儿法》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

MD5 加密
MD5 加密

MD5 加密工具