colindunn
colindunn

Reputation: 3163

Swift: How to use property observers with delegation

I'm trying to use delegation and property observers together to know when a property changes. I setup the protocol but I'm not sure how to use property observers.

I have a class called GridView that is being added to DetailViewController. GridView has an array of ints called rowValues. I would like to observe rowValues from DetailViewController.

GridView.swift

protocol gridViewDelegate {
    func rowValueChanged(value: [Int])
}

class GridView: UIView {

    var rowValues = [0,0,0,0,0]
    var delegate: gridViewDelegate?

    func updateRowValue() {
        rowValues[0] = 1
    }
}

DetailViewController.swift

class DetailViewController: UIViewController, gridViewDelegate {

      override func viewDidLoad() {
          super.viewDidLoad()

          var grid = GridView(frame: view.frame)
          grid.delegate = self
          view.addSubview(grid)
      }

      func rowValueChanged(value: [Int]) {
          println(value)
      }  
}

Upvotes: 2

Views: 462

Answers (1)

Matteo Piombo
Matteo Piombo

Reputation: 6726

Probably this is the syntax you are looking for:

class GridView: UIView {

    var rowValues: [Int] = [0,0,0,0,0] {
        didSet {
            if let theDelegate = self.delegate {
                theDelegate.rowValueChanged(rowValues)
            }
        }
    }
    var delegate: gridViewDelegate?

}

Upvotes: 4

Related Questions