Skip to content

Instantly share code, notes, and snippets.

@christopher-fuller
Last active November 11, 2016 19:03
Show Gist options
  • Save christopher-fuller/eb5e8156d91a7927cc5514ddefaed59d to your computer and use it in GitHub Desktop.
Save christopher-fuller/eb5e8156d91a7927cc5514ddefaed59d to your computer and use it in GitHub Desktop.
//
// ViewUpdatingContext.swift
// Created by Christopher Fuller for Southern California Public Radio
// Original version at https://github.com/SCPR/swift-experiments/blob/master/source/InterfaceUpdatable.swift
// Updated by Christopher Fuller for Swift 3 compatibility
//
// Copyright (c) 2016 Southern California Public Radio
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class ViewUpdatingContext {
typealias ViewUpdater = NotificationObserver
var animated: Bool
private var _animated: Bool?
private let observer = NotificationObservingContext() // Source: https://git.io/vXl07
private let coalescer = NotificationCoalescingContext() // Source: https://git.io/vXlai
init(animated: Bool = false) {
self.animated = animated
observer.observe(.UIApplicationWillEnterForeground) {
[ weak self ] _, _ in
guard let _self = self else { return }
_self.update()
}
}
@discardableResult func onUpdate(_ closure: @escaping (_ animated: Bool) -> Void) -> ViewUpdater {
return coalescer.observe {
[ weak self ] (_, _: UpdateViewNotification) in
guard let _self = self else { return }
let animated = _self._animated
_self._animated = nil
closure(animated ?? _self.animated)
}
}
func removeUpdaters() {
coalescer.removeObservers()
}
func setNeedsUpdate(animated: Bool? = nil) {
if let animated = animated {
if animated, let animated = self._animated, !animated {
update()
}
self._animated = animated
}
coalescer.enqueue(UpdateViewNotification())
}
func update(animated: Bool? = nil) {
if let animated = animated {
self._animated = animated
}
coalescer.enqueue(UpdateViewNotification(), postingStyle: .now)
}
}
private extension ViewUpdatingContext {
struct UpdateViewNotification: ObservableNotification {}
}
@christopher-fuller
Copy link
Author

What is ViewUpdatingContext?

ViewUpdatingContext enables view controllers to update their views in a run-loop efficient manner.

A view controller calls setNeedsUpdate to indicate that its view should update, and should do this whenever state that affects the UI changes.

Requests to update the view are coalesced and the onUpdate callback is called as few times as possible per run loop, typically only once.

@christopher-fuller
Copy link
Author

Example Usage

import UIKit

class ExampleViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    private lazy var updater: ViewUpdatingContext = {
        // Decide if updates should be animated by default:
        let updater = ViewUpdatingContext(animated: false) // Equivalent to: ViewUpdatingContext()
        updater.onUpdate {
            // Must capture self weakly to avoid retain cycle:
            [ weak self ] animated in
            self?.updateUI(animated: animated)
        }
        return updater
    }()

    private var text = "Hello World!" {
        didSet {
            // Call setNeedsUpdate() whenever state changes and/or UI needs to be updated:
            updater.setNeedsUpdate()
        }
    }

    private var textColor = UIColor.black {
        didSet {
            // Pass animated if you want to override the default updating behavior for the next update:
            updater.setNeedsUpdate(animated: true)
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // Always call update() in viewWillAppear:
        updater.update()
    }

    private func updateUI(animated: Bool) {
        // Update the user interface:
        let changes = {
            // Can capture self strongly since closure is called synchronously:
            self.label.text = self.text
            self.label.textColor = self.textColor
        }
        if animated {
            UIView.animate(withDuration: 0.3, animations: changes)
        } else {
            changes()
        }
    }

}

@christopher-fuller
Copy link
Author

Example Usage

In this example, another object (ExampleObject ) let's the view controller know when it should update it's UI. This technique is useful when the view controller relies on the state of other objects. This method can be combined with the first example.

import UIKit

class ExampleViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    private lazy var updater: ViewUpdatingContext = {
        let updater = ViewUpdatingContext()
        updater.onUpdate {
            [ weak self ] animated in
            self?.updateUI(animated: animated)
        }
        return updater
    }()

    // Some other object that will let the view controller know it should update it's user interface:
    private lazy var object: ExampleObject = {
        // This object must use the same context:
        return ExampleObject(viewUpdater: self.updater)
    }()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updater.update()
    }

    private func updateUI(animated: Bool) {
        let changes = {
            self.label.text = self.object.text
            self.label.textColor = self.object.textColor
        }
        if animated {
            UIView.animate(withDuration: 0.3, animations: changes)
        } else {
            changes()
        }
    }

}

class ExampleObject {

    private let viewUpdater: ViewUpdatingContext

    var text = "Hello World!" {
        didSet {
            viewUpdater.setNeedsUpdate()
        }
    }

    var textColor = UIColor.black {
        didSet {
            viewUpdater.setNeedsUpdate(animated: true)
        }
    }

    init(viewUpdater: ViewUpdatingContext) {
        self.viewUpdater = viewUpdater
    }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment