天天看点

关于swift中KVO的简单使用

通过kvo实现视图背景颜色的轮换

关于swift中KVO的简单使用
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let model = ColorModel()
        let myView = ColorView(frame: CGRectMake(80,100,240,300))
        myView.model = model
        view.addSubview(myView)
    }

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


}
      
class ColorModel: NSObject {
    //颜色属性
    //KVO观察的属性必须是dynamic
    dynamic var color: UIColor?
    //定时器
    var timer: NSTimer?
    override init() {
        super.init()
        //创建定时器
        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(timeAction), userInfo: nil, repeats: true)
    }
    func timeAction(){
        color = UIColor(red: CGFloat(arc4random()%256)/255.0, green: CGFloat(arc4random()%256)/255.0, blue: CGFloat(arc4random()%256)/255.0, alpha: 1.0)
    }
}
           
关于swift中KVO的简单使用

这个是colorView视图里面的实现 在ColorView里面定义colorModel类的模型,具体看图

class ColorView: UIView {
    var model: ColorModel? {
        didSet{
            //实现ColorView对象对ColorModel对象的观察
            //1、被观察者对象调用这个方法
            /*
             第一个参数:观察者对象
             第二个参数:观察的属性
             第三个参数:观察的属性的什么值(新值,旧值等)
             第四个参数:nil
             */
            model?.addObserver(self, forKeyPath: "color", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
     //2.观察者对象所属的类型实现下面的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer
   
    ) {
        /*
         第一个参数:属性
         第二个参数:被观察者对象
         第三个参数:属性变化信息
         第四个参数:上下文nil
         */
        //获取属性变化值
        let newColor = change!["new"] as! UIColor
        backgroundColor = newColor
    }
}

   
           
关于swift中KVO的简单使用
关于swift中KVO的简单使用