Coder Social home page Coder Social logo

eureka's Introduction

Eureka: Elegant form builder in Swift

Build status Platform iOS Swift 2 compatible Carthage compatible CocoaPods compatible License: MIT

By XMARTLABS. This is the re-creation of XLForm in Swift 2. If you have been using it then many terms will result familiar to you.

Introduction

Eureka! is a library to create dynamic table-view forms from a DSL specification in Swift. This DSL basically consists of Rows, Sections and Forms. A Form is a collection of Sections and a Section is a collection of Rows.

Both Form and Section classes conform to MutableCollectionType and RangeReplaceableCollectionType protocols. This makes a whole bunch of functions available to be executed on them.

For more information look at our blog post that introduces Eureka!.

Requirements

  • iOS 8.0+
  • Xcode 7.0+

Getting involved

  • If you want to contribute please feel free to submit pull requests.
  • If you have a feature request please open an issue.
  • If you found a bug or need help please check older issues or threads on StackOverflow (tag 'eureka') before submitting an issue.

If you use Eureka in your app We would love to hear about it! Drop us a line on twitter.

Examples

Follow these 3 steps to run Example project: Clone Eureka repository, open Eureka workspace and run the Example project.

You can also experiment and learn with the Eureka Playground which is contained in Eureka.workspace.

Usage

How to create a form

It is quite simple to create a form, just like this:

import Eureka

class CustomCellsController : FormViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        form +++ Section("Custom cells")
	            	<<< WeekDayRow(){
	            		$0.value = [.Monday, .Wednesday, .Friday]
	            	}
	            	<<< FloatLabelRow() {
	            		$0.title = "Float Label Row, type something to see.."
	            	}
    }
}

In this example we create a CustomCellsController and then simply add a section with two custom rows to the form variable inherited from FormViewController. And this is the product:

Screenshot of Custom Cells

Operators

We declared a series of custom operators to make the creation and modification of forms more readable and appealing.

+++=

This operator is used to append a row or section to a form. In case you are appending a row, then a section will be created that contains that row and that section will be appended to the form.

// Will append a section at the end of the 'form' Form.
form +++= Section()

// Will internally create a Section containing a PhoneRow and append it to the 'form' variable:
form +++= PhoneRow()

+++

Lets you add a Section to a Form or create a Form by adding two sections. For example:

// Will add two sections at the end of the 'form' Form.
form +++ Section("Custom cells") +++ Section("Another section")

// Will create and assign a Form to the 'form' variable (containing the two sections):
form = Section("Custom cells") +++ Section("Another section")

<<<

This one is used to append rows to sections or to create a Section by appending two rows. For example:

// Will append a Check row to the last section of the 'form' Form.
form.last! <<< CheckRow()

// Will implicitly create a Section and add it to the 'form' (containing the two rows):
form +++ PhoneRow("Phone"){ $0.title = "Phone"}
         <<< IntRow("IntRow"){ $0.title = "Int"; $0.value = 5 }

+=

This operator just invokes the corresponding appendContentsOf method which means that it can be used to append arrays of elements to either a Form or a Section like this:

// Will append three sections to form.
form += [Section("A"), Section("B"), Section("C")]
To learn more about these operators try them out in Eureka Playground.

Rows

This is a list of the rows that are provided by default:

  • Field Rows This rows have a textfield on the right side of the cell. The difference between each one of them consists in a different capitalization, autocorrection and keyboard type configuration.

    • TextRow
    • NameRow
    • UrlRow
    • IntRow
    • PhoneRow
    • PasswordRow
    • EmailRow
    • DecimalRow
    • TwitterRow
    • AccountRow
  • Date Rows This rows have an UIDatePicker attached that will appear at the bottom of the screen. The mode of the UIDatePicker is what changes between them.

    • DateRow
    • TimeRow
    • DateTimeRow
    • CountDownRow
  • Options Selector Rows These are rows with a list of options associated from which the user must choose. You can see them in the examples above.

    • AlertRow
    Screenshot of Custom Cells
    • ActionSheetRow

      The ActionSheetRow will show an action sheet with options to choose from.

    • SegmentedRow

    Screenshot of Segment Row
    • PushRow

      This row will push to a new controller from where to choose options listed using Check rows.

    • ImageRow

      Will let the user pick a photo

    • MultipleSelectorRow

      This row allows the selection of multiple options

    • LocationRow (Included as custom row in the the example project)

      Screenshot of Location Row
  • Other Rows These are other rows that might be useful

    • ButtonRow
    • CheckRow
    • LabelRow
    • SwitchRow
    • TextAreaRow

There are also some custom rows in the examples project.

Customization

A row holds the basic information that will be displayed on a cell like title, value, options (if present), etc. All the stuff that has to do with appearance like colors, fonts, text alignments, etc. normally go in the cell. Both, the row and the cell hold a reference to each other.

You will often want to customize how a row behaves when it is tapped on or when its value changes and you might be interested in changing its appearance as well. There are currently 5 callbacks to change the default appearance and behaviour of a row.

  • onChange()

    This will be called when the value of a row changes. You might be interested in adjusting some parameters here or even make some other rows appear or disappear.

  • onCellSelection()

    This one will be called each time the user taps on the row and it gets selected.

  • cellSetup()

    The cellSetup will be called once when the cell is first configured. Here you should set up your cell with its permanent settings.

  • cellUpdate()

    The cellUpdate will be called each time the cell appears on screen. Here you can change how the title and value of your row is set or change the appearance (colors, fonts, etc) depending on variables that might not be present at cell creation time.

  • onPresent()

    This method will be called by a row just before presenting another view controller. This does only apply to the rows conforming to the PresenterRowType protocol. You can use this to set up the presented controller.

Each row also has an initializer where you should set the basic attributes of the row.

Here is an example:

let row  = CheckRow("set_disabled") { // initializer
              $0.title = "Stop at disabled row"
              $0.value = self.navigationOptions?.contains(.StopDisabledRow)
           }.onChange { [weak self] row in
              if row.value ?? false {
                  self?.navigationOptions = self?.navigationOptions?.union(.StopDisabledRow)
              }
              else{
                  self?.navigationOptions = self?.navigationOptions?.subtract(.StopDisabledRow)
              }
           }.cellSetup { cell, row in
              cell.backgroundColor = .lightGrayColor()
           }.cellUpdate { cell, row in
              cell.textLabel?.font = .italicSystemFontOfSize(18.0)
           }

Now it would look like this:

Screenshot of Disabled Row

How to create custom rows and cells

To create a custom row you will have to create a new class subclassing from Row<ValueType, CellType> and conforming to RowType protocol. Take for example the SwitchRow:

public final class SwitchRow: Row<Bool, SwitchCell>, RowType {

    required public init(tag: String?) {
        super.init(tag: tag)
        displayValueFor = nil
    }
}

Most times you will want to create a custom cell as well as most of the specific logic is here. What you have to do is subclassing Cell:

public class SwitchCell : Cell<Bool> {

    required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }

    public var switchControl: UISwitch? {
        return accessoryView as? UISwitch
    }

    public override func setup() {
        super.setup()
        selectionStyle = .None
        accessoryView = UISwitch()
        editingAccessoryView = accessoryView
        switchControl?.addTarget(self, action: "valueChanged", forControlEvents: .ValueChanged)
    }

    public override func update() {
        super.update()
        switchControl?.on = formRow.value ?? false
        switchControl?.enabled = !formRow.isDisabled
    }

    func valueChanged() {
        formRow.value = switchControl?.on.boolValue ?? false
    }
}

The setup and update methods are similar to the cellSetup and cellUpdate callbacks and that is where the cell should be customized.

Note: ValueType and CellType are illustrative. You have to replace them with the type your value will have and the type of your cell (like Bool and SwitchCell in this example)

How to dynamically hide and show rows (or sections)

Many forms have conditional rows, I mean rows that might appear on screen depending on the values of other rows. You might want to have a SegmentedRow at the top of your screen and depending on the chosen value ask different questions:

Screenshot of Hidden Rows

In this case we are hiding and showing whole sections

To accomplish this each row has an hidden variable that is of optional type Condition.

public enum Condition {
    case Predicate(NSPredicate)
    case Function([String], (Form?)->Bool)
}

The hidden variable might be set with a function that takes the form the row belongs to and returns a Bool that indicates whether the row should be hidden or not. This is the most powerful way of setting up this variable as there are no explicit limitations as to what can be done in the function.

Along with the function you have to pass an array with all the tags of the rows this row depends on. This is important so that Eureka can reevaluate the function each time a value changes that may change the result of this function. In fact that will be the only time the function is reevaluated. You can define it like this:

<<< AlertRow<Emoji>("tag1") {
        $0.title = "AlertRow"
        $0.optionTitle = "Who is there?"
        $0.options = [๐Ÿ’, ๐Ÿ, ๐Ÿ‘ฆ, ๐Ÿ—, ๐Ÿผ, ๐Ÿป]
        $0.value = ๐Ÿ‘ฆ
    }
   // ...
<<< PushRow<Emoji>("tag2") {
        $0.title = "PushRow"
        $0.options = [๐Ÿ’, ๐Ÿ, ๐Ÿ‘ฆ, ๐Ÿ—, ๐Ÿผ, ๐Ÿป]
        $0.value = ๐Ÿ‘ฆ
        $0.hidden = Condition.Function(["tag1"]) { form in
                        if let r1 : AlertRow<Emoji> = form?.rowByTag("tag1") {
                            return r1.value == ๐Ÿ‘ฆ
                        }
                        return false
                    }
      }

The hidden variable can also be set with a NSPredicate. In the predicate string you can reference values of other rows by their tags to determine if a row should be hidden or visible. This will only work if the values of the rows the predicate has to check are NSObjects (String and Int will work as they are bridged to their ObjC counterparts, but enums won't work). Why could it then be useful to use predicates when they are more limited? Well, they can be much simpler, shorter and readable than functions. Look at this example:

$0.hidden = Condition.Predicate(NSPredicate(format: "$switchTag == false"))

And we can write it even shorter since Condition conforms to StringLiteralConvertible:

$0.hidden = "$switchTag == false"

Note: we will substitute the value of the row whose tag is 'switchTag' instead of '$switchTag'

For all of this to work, all of the implicated rows must have a tag as the tag will identify them.

We can also hide a row by doing:

$0.hidden = true

as Condition conforms to BooleanLiteralConvertible.

Not setting the hidden variable will leave the row always visible.

Sections

For sections this works just the same. That means we can set up section hidden property to show/hide it dynamically.

Disabling rows

To disable rows, each row has an disabled variable which is also an optional Condition type property . This variable also works the same as the hidden variable so that it requires the rows to have a tag.

Note that if you want to disable a row permanently you can also set disabled variable to true.

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects.

Specify Eureka into your project's Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'Eureka', '~> 1.0'

Then run the following command:

$ pod install

Carthage

Carthage is a simple, decentralized dependency manager for Cocoa.

Specify Eureka into your project's Cartfile:

github "xmartlabs/Eureka" ~> 1.0

Manually as Embedded Framework

  • Clone Eureka as a git submodule by running the following command from your project root git folder.
$ git submodule add https://github.com/xmartlabs/Eureka.git
  • Open Eureka folder that was created by the previous git submodule command and drag the Eureka.xcodeproj into the Project Navigator of your application's Xcode project.

  • Select the Eureka.xcodeproj in the Project Navigator and verify the deployment target matches with your application deployment target.

  • Select your project in the Xcode Navigation and then select your application target from the sidebar. Next select the "General" tab and click on the + button under the "Embedded Binaries" section.

  • Select Eureka.framework and we are done!

Authors

FAQ

How to change the bottom navigation accessory view?

To change the behaviour of this you should set the navigation options of your controller. The FormViewController has a navigationOptions variable which is an enum and can have one or more of the following values:

  • None: no view at all
  • Enabled: enable view at the bottom
  • StopDisabledRow: if the navigation should stop when the next row is disabled
  • SkipCanNotBecomeFirstResponderRow: if the navigation should skip the rows that return false to canBecomeFirstResponder()

The default value is Enabled & SkipCanNotBecomeFirstResponderRow

If you want to change the whole view of the bottom you will have to override the navigationAccessoryView variable in your subclass of FormViewController.

eureka's People

Contributors

mtnbarreto avatar

Watchers

 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.