简体   繁体   English

财产观察员迅速改变颜色

[英]Property Observer for color change in swift

I've successfully created a simple iOS app that will change the background color When I click on the button. 我已经成功创建了一个简单的iOS应用,该应用将在单击按钮时更改背景色。 But. 但。 now the problem is I've no idea on how to implement property observer to print out message to the effect of the color whenever the color has changed. 现在的问题是,我不知道如何实现属性观察器以在颜色改变时将消息打印出具有颜色效果的信息。

UIColorExtension.swift

 import UIKit
 extension UIColor {

      static var random: UIColor {
        // Seed (only once)
        srand48(Int(arc4random()))
        return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0)
      }
 }

ViewController.Swift

 import UIKit

 class ViewController: UIViewController {

      override func viewDidLoad() {
           super.viewDidLoad()

           // apply random color on view did load
           applyRandomColor()
       }


       @IBAction func btnHandler(_ sender: Any) {

           // on each button click, apply random color to view
           applyRandomColor()
       }

       func applyRandomColor() {
           view.backgroundColor = UIColor.random
       }
}

Please teach me on how to use property observer to monitor and print the color each time the color is changed as I don't have the slightest idea to do so. 请教我如何在每次更改颜色时使用属性观察器监视和打印颜色,因为我丝毫没有丝毫想法。

At the moment you're just doing this 目前,您正在执行此操作

 view.backgroundColor = X

instead, you probably want to make your own "property".... 相反,您可能想制作自己的“财产”。

 var mood: UIColor { }

properties can have a "didSet" action... 属性可以具有“ didSet”操作...

 var mood: UIColor {
    didSet {
       view.backgroundColor = mood
       print("Hello!")
    }
 }

So now, just use "mood" when you want to change the background color. 因此,现在,当您要更改背景颜色时,只需使用“心情”即可。

mood = X

But, you can ALSO run any other code - where it prints the Hello. 但是,您还可以运行任何其他代码-在该代码中打印Hello。

Imagine your program has 100s of places where you do this thing of changing the background color . 想象一下,您的程序有100多个位置,您可以在其中进行更改背景颜色的操作

If you use a property, you can change what happens "all at once" by just changing the code at print("Hello"). 如果使用属性,则只需更改print(“ Hello”)上的代码,即可“立即”更改所有操作。

Otherwise, you'd have to change every one of the 100s of places where you do that. 否则,您必须更改执行此操作的100个位置中的每个位置。

This is a real basic in programming. 这是编程的真正基础。 Enjoy! 请享用!

If you really need an observer Swift 4 provides a very smart way to do that: 如果您真的需要观察者,Swift 4提供了一种非常聪明的方法:

  • Declare a NSKeyValueObservation property 声明一个NSKeyValueObservation属性

     var observation : NSKeyValueObservation? 
  • In viewDidLoad add the observer, the closure is executed whenever the background color changes. viewDidLoad添加观察者,只要背景颜色发生变化,就执行关闭。

     observation = observe(\\.view.backgroundColor, options: [.new]) { _, change in print(change.newValue!) } 

In Swift there are two types of property observers ie: 在Swift中,有两种类型的属性观察器,即:

willSet willSet

didSet didSet

You can find it in the Swift documentation here . 您可以雨燕文档中找到它这里

if you just need to print color description using property observer then you can create property and set its observers like this: 如果仅需要使用属性观察器打印颜色描述,则可以创建属性并设置其观察器,如下所示:

var backgroundColor = UIColor() {
    didSet {
        print("didSet value : \(backgroundColor)")
    }
}

and your complete code will look like: 您的完整代码将如下所示:

import UIKit

class ViewController: UIViewController {

    var backgroundColor = UIColor() {
        didSet {
            print("didSet value : \(backgroundColor)")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.applyRandomColor()
    }

    @IBAction func btnHandler(_ sender: Any) {

        // on each button click, apply random color to view
        applyRandomColor()

    }

    func applyRandomColor() {
        backgroundColor = UIColor.random
        self.view.backgroundColor = backgroundColor

    }


}

extension UIColor {

    static var random: UIColor {
        // Seed (only once)
        srand48(Int(arc4random()))
        return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue:
            CGFloat(drand48()), alpha: 1.0)
    }
}

First of all you don't need any observer here because you know when the color is changing as it is changing by you manually by calling the applyRandomColor() function. 首先,您在这里不需要任何观察者,因为您可以通过调用applyRandomColor()函数手动知道颜色的变化时间。 So you can do here whatever you want to do. 因此,您可以在这里做任何想做的事情。

After that if you still want to see how observer works. 之后,如果您仍然想看看观察者是如何工作的。 Then add an observer in class where you want to observe this event. 然后在要观察此事件的类中添加观察者。

view.addObserver(self, forKeyPath: "backgroundColor", options: NSKeyValueObservingOptions.new, context: nil)

And here is the event: 这是事件:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
      if keyPath == "backgroundColor" {
          /// Background color has changed
          /// Your view which backgroundColor it is
          guard let view = object as? UIView else {return}
          print(view.backgroundColor)
                    OR
          guard let color = change?[.newKey] as? UIColor else {return}
          print(color)
      }
}

First add observer like this: 首先像这样添加观察者:

view.addObserver(self, forKeyPath: "backgroundColor", options: [.new], context: nil)

Then override the function: 然后覆盖函数:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    guard let color = change?[.newKey] as? UIColor else {return}
    print(color)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM