F. Bai F. Bai - 5 months ago 20x
Swift Question

iOS - view controller respond to data change from uiview

I am using a color picker (UIView subclass) in my view controller written by someone else, and it contains several subviews that handles touch events. The color picker has a public variable "color", and it's updated when user interacts with the subviews.

public class SwiftHSVColorPicker: UIView {
var colorWheel: ColorWheel!

public var color: UIColor!

See: https://github.com/johankasperi/SwiftHSVColorPicker/blob/master/Source/SwiftHSVColorPicker.swift

I have referenced this color picker view and a label in my view controller:

@IBOutlet weak var colorPicker: SwiftHSVColorPicker!
@IBOutlet weak var output: UILabel!

How can I update the label text whenever the "color" data change from the color picker view?


If possible you need to modify it there are two ways :


var colorChanged : ((UIColor!)->())?// add a callback for the colorpicker

func hueAndSaturationSelected(hue: CGFloat, saturation: CGFloat) {
    self.hue = hue
    self.saturation = saturation
    self.color = UIColor(hue: self.hue, saturation: self.saturation, brightness: self.brightness, alpha: 1.0)

    self.colorChanged?(self.color) //call it at this method


colorPicker.colorChanged = {[weak self]  color in

        self?.label.textColor = color //do something with your label



dynamic public var color: UIColor! // add the dynamic keyword
colorPicker.addObserver(self, forKeyPath: "color", options:[.Initial, .New], context: nil) // add an observer for the color 

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    //do something with the color
    if let color = change![NSKeyValueChangeNewKey] as? UIColor {
        self.label.textColor = color