Coder Social home page Coder Social logo

yonaskolb / statefulviewcontroller Goto Github PK

View Code? Open in Web Editor NEW

This project forked from aschuch/statefulviewcontroller

0.0 2.0 0.0 447 KB

Placeholder views based on content, loading, error or empty states

License: MIT License

Swift 94.92% Ruby 3.01% Objective-C 2.07%

statefulviewcontroller's Introduction

StatefulViewController

Build Status Carthage compatible Swift 2

A protocol to enable UIViewControllers or UIViews to present placeholder views based on content, loading, error or empty states.

StatefulViewController Example

In a networked application a view controller or custom view typically has the following states that need to be communicated to the user:

  • Loading: The content is currently loaded over the network.
  • Content: The content is available and presented to the user.
  • Empty: There is currently no content available to display.
  • Error: An error occured whilst downloading content.

As trivial as this flow may sound, there are a lot of cases that result in a rather large decision tree.

Decision Tree

StatefulViewController is a concrete implementation of this particular decision tree. (If you want to create your own modified version, you might be interested in the state machine that is used to show and hide views.)

Usage

This guide describes the use of the StatefulViewController protocol on UIViewController. However, you can also adopt the StatefulViewController protocol on any UIViewController subclass, such as UITableViewController or UICollectionViewController, as well as your custom UIView subclasses.

First, make sure your view controller adopts to the StatefulViewController protocol.

class MyViewController: UIViewController, StatefulViewController {
    // ...
}

Then, configure the loadingView, emptyView and errorView properties (provided by the StatefulViewController protocol) in viewDidLoad.

override func viewDidLoad() {
    super.viewDidLoad()
    
    // Setup placeholder views
    loadingView = // UIView
    emptyView = // UIView
    errorView = // UIView
}

In addition, call the setupInitialViewState() method in viewWillAppear: in order to setup the initial state of the controller.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
        
    setupInitialViewState()
}

After that, simply tell the view controller whenever content is loading and StatefulViewController will take care of showing and hiding the correct loading, error and empty view for you.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
        
    loadDeliciousWines()
}

func loadDeliciousWines() {
	startLoading()
	
	let url = NSURL(string: "http://example.com/api")
	let session = NSURLSession.sharedSession()
	session.dataTaskWithURL(url) { (let data, let response, let error) in
		endLoading(error: error)
	}.resume()
}

Life cycle

StatefulViewController calls the hasContent method to check if there is any content to display. If you do not override this method in your own class, StatefulViewController will always assume that there is content to display.

func hasContent() -> Bool {
	return datasourceArray.count > 0
}

Optionally, you might also be interested to respond to an error even if content is already shown. StatefulViewController will not show its errorView in this case, because there is already content that can be shown.

To e.g. show a custom alert or other unobtrusive error message, use handleErrorWhenContentAvailable: to manually present the error to the user.

func handleErrorWhenContentAvailable(error: ErrorType) {
	let alertController = UIAlertController(title: "Ooops", message: "Something went wrong.", preferredStyle: .Alert)
	alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
	self.presentViewController(alertController, animated: true, completion: nil)
}

View State Machine

Note: The following section is only intended for those, who want to create a stateful controller that differs from the flow described above.

You can also use the underlying view state machine to create a similar implementation for your custom flow of showing/hiding views.

let stateMachine = ViewStateMachine(view: view)

// Add states
stateMachine["loading"] = loadingView
stateMachine["other"] = otherView

// Transition to state
stateMachine.transitionToState(.View("loading"), animated: true) {
	println("finished switching to loading view")
}

// Hide all views
stateMachine.transitionToState(.None, animated: true) {
	println("all views hidden now")
}

Installation

Carthage

Add the following line to your Cartfile.

github "aschuch/StatefulViewController", ~> 1.0

Then run carthage update.

Cocoapods

Add the following line to your Podfile.

pod "StatefulViewController", "~> 1.0"

Then run pod install with Cocoapods 0.36 or newer.

Manually

Just drag and drop the two .swift files in the StatefulViewController folder into your project.

Tests

Open the Xcode project and press โŒ˜-U to run the tests.

Alternatively, all tests can be run from the terminal using xctool.

xctool -scheme StatefulViewControllerTests -sdk iphonesimulator test

Todo

  • Default loading, error, empty views
  • Protocol on views that notifies them of removal and add
  • Views can provide delays in order to tell the state machine to show/remove them only after a specific delay (e.g. for hide and show animations)

Contributing

  • Create something awesome, make the code better, add some functionality, whatever (this is the hardest part).
  • Fork it
  • Create new branch to make your changes
  • Commit all your changes to your branch
  • Submit a pull request

Contact

Feel free to get in touch.

statefulviewcontroller's People

Contributors

aschuch avatar yonaskolb avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.