Swift iOS:KVO

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

内容简介: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'

以上所述就是小编给大家介绍的《Swift iOS:KVO》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

REST in Practice

REST in Practice

Jim Webber、Savas Parastatidis、Ian Robinson / O'Reilly Media / 2010-9-24 / USD 44.99

Why don't typical enterprise projects go as smoothly as projects you develop for the Web? Does the REST architectural style really present a viable alternative for building distributed systems and ent......一起来看看 《REST in Practice》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具