Made with ❤️ byXMARTLABS.This is the re-creation ofXLFormin Swift.
For more information look atour blog postthat introducesEureka.
- Xcode 11+
- Swift 5.0+
You can clone and run the Example project to see examples of most of Eureka's features.
By extendingFormViewController
you can then simply add sections and rows to theform
variable.
import Eureka
classMyFormViewController:FormViewController{
overridefuncviewDidLoad(){
super.viewDidLoad()
form+++Section("Section1")
<<<TextRow(){rowin
row.title="Text Row"
row.placeholder="Enter text here"
}
<<<PhoneRow(){
$0.title="Phone Row"
$0.placeholder="And numbers here"
}
+++Section("Section2")
<<<DateRow(){
$0.title="Date Row"
$0.value=Date(timeIntervalSinceReferenceDate:0)
}
}
}
In the example we create two sections with standard rows, the result is this:
You could create a form by just setting up theform
property by yourself without extending fromFormViewController
but this method is typically more convenient.
To change the behaviour of this you should set the navigation options of your controller. TheFormViewController
has anavigationOptions
variable which is an enum and can have one or more of the following values:
- disabled: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 isenabled & skipCanNotBecomeFirstResponderRow
To enable smooth scrolling to off-screen rows, enable it via theanimateScroll
property. By default, theFormViewController
jumps immediately between rows when the user hits the next or previous buttons in the keyboard navigation accesory, including when the next row is off screen.
To set the amount of space between the keyboard and the highlighted row following a navigation event, set therowKeyboardSpacing
property. By default, when the form scrolls to an offscreen view no space will be left between the top of the keyboard and the bottom of the row.
classMyFormViewController:FormViewController{
overridefuncviewDidLoad(){
super.viewDidLoad()
form=...
// Enables the navigation accessory and stops navigation when a disabled row is encountered
navigationOptions=RowNavigationOptions.Enabled.union(.StopDisabledRow)
// Enables smooth scrolling on navigation to off-screen rows
animateScroll=true
// Leaves 20pt of space between the keyboard and the highlighted row after scrolling to an off screen row
rowKeyboardSpacing=20
}
}
If you want to change the whole navigation accessory view, you will have to override thenavigationAccessoryView
variable in your subclass ofFormViewController
.
TheRow
object holds avalueof a specific type.
For example, aSwitchRow
holds aBool
value, while aTextRow
holds aString
value.
// Get the value of a single row
letrow:TextRow?=form.rowBy(tag:"MyRowTag")
letvalue=row.value
// Get the value of all rows which have a Tag assigned
// The dictionary contains the 'rowTag':value pairs.
letvaluesDictionary=form.values()
Eureka includes custom operators to make form creation easy:
form+++Section()
// Chain it to add multiple Sections
form+++Section("First Section")+++Section("Another Section")
// Or use it with rows and get a blank section for free
form+++TextRow()
+++TextRow()// Each row will be on a separate section
form+++Section()
<<<TextRow()
<<<DateRow()
// Or implicitly create the Section
form+++TextRow()
<<<DateRow()
// Append Sections into a Form
form+=[Section("A"),Section("B"),Section("C")]
// Append Rows into a Section
section+=[TextRow(),DateRow()]
Eureka includes result builders to make form creation easy:
// Section + Section
form=(Section("A")+++{
URLRow("UrlRow_f1"){$0.title="Url"}
if something{
TwitterRow("TwitterRow_f2"){$0.title="Twitter"}
}else{
TwitterRow("TwitterRow_f1"){$0.title="Twitter"}
}
AccountRow("AccountRow_f1"){$0.title="Account"}
})
// Form + Section
form+++{
if something{
PhoneRow("PhoneRow_f1"){$0.title="Phone"}
}else{
PhoneRow("PhoneRow_f2"){$0.title="Phone"}
}
PasswordRow("PasswordRow_f1"){$0.title="Password"}
}
@FormBuilder
varform:Form{
Section("Section A"){sectionin
section.tag="Section_A"
}
if true{
Section("Section B"){sectionin
section.tag="Section_B"
}
}
NameRow("NameRow_f1"){$0.title="Name"}
}
Eureka includes callbacks to change the appearance and behavior of a row.
ARow
is an abstraction Eureka uses which holds avalueand contains the viewCell
.TheCell
manages the view and subclassesUITableViewCell
.
Here is an example:
letrow=SwitchRow("SwitchRow"){rowin// initializer
row.title="The title"
}.onChange{rowin
row.title=(row.value??false)?"The title expands when on":"The title"
row.updateCell()
}.cellSetup{cell,rowin
cell.backgroundColor=.lightGray
}.cellUpdate{cell,rowin
cell.textLabel?.font=.italicSystemFont(ofSize:18.0)
}
-
onChange()
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()
Called each time the user taps on the row and it gets selected. Note that this will also get called for disabled rows so you should start your code inside this callback with something like
guard!row.isDisabled else { return }
-
cellSetup()
Called only once when the cell is first configured. Set permanent settings here.
-
cellUpdate()
Called each time the cell appears on screen. You can change the appearance here using variables that may not be present on cellSetup().
-
onCellHighlightChanged()
Called whenever the cell or any subview become or resign the first responder.
-
onRowValidationChanged()
Called whenever the the validation errors associated with a row changes.
-
onExpandInlineRow()
Called before expanding the inline row. Applies to rows conforming
InlineRowType
protocol. -
onCollapseInlineRow()
Called before collapsing the inline row. Applies to rows conforming
InlineRowType
protocol. -
onPresent()
Called by a row just before presenting another view controller. Applies to rows conforming
PresenterRowType
protocol. Use it to set up the presented controller.
You can set a titleString
or a customView
as the header or footer of aSection
.
Section("Title")
Section(header:"Title",footer:"Footer Title")
Section(footer:"Footer Title")
You can use a Custom View from a.xib
file:
Section(){sectionin
varheader=HeaderFooterView<MyHeaderNibFile>(.nibFile(name:"MyHeaderNibFile",bundle:nil))
// Will be called every time the header appears on screen
header.onSetupView={view,_in
// Commonly used to setup texts inside the view
// Don't change the view hierarchy or size here!
}
section.header=header
}
Or a customUIView
created programmatically
Section(){sectionin
varheader=HeaderFooterView<MyCustomUIView>(.class)
header.height={100}
header.onSetupView={view,_in
view.backgroundColor=.red
}
section.header=header
}
Or just build the view with a Callback
Section(){sectionin
section.header={
varheader=HeaderFooterView<UIView>(.callback({
letview=UIView(frame:CGRect(x:0,y:0,width:100,height:100))
view.backgroundColor=.red
returnview
}))
header.height={100}
returnheader
}()
}
In this case we are hiding and showing whole sections.
To accomplish this each row has ahidden
variable of optional typeCondition
which can be set using a function orNSPredicate
.
Using thefunction
case ofCondition
:
Condition.function([String],(Form)->Bool)
The array ofString
to pass should contain the tags of the rows this row depends on. Each time the value of any of those rows changes the function is reevaluated.
The function then takes theForm
and returns aBool
indicating whether the row should be hidden or not. This the most powerful way of setting up thehidden
property as it has no explicit limitations of what can be done.
form+++Section()
<<<SwitchRow("switchRowTag"){
$0.title="Show message"
}
<<<LabelRow(){
$0.hidden=Condition.function(["switchRowTag"],{formin
return!((form.rowBy(tag:"switchRowTag")as?SwitchRow)?.value??false)
})
$0.title="Switch is on!"
}
publicenumCondition{
casefunction([String],(Form)->Bool)
casepredicate(NSPredicate)
}
Thehidden
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 sinceCondition
conforms toExpressibleByStringLiteral
:
$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 tagas the tag will identify them.
We can also hide a row by doing:
$0.hidden=true
asCondition
conforms toExpressibleByBooleanLiteral
.
Not setting thehidden
variable will leave the row always visible.
If you manually set the hidden (or disabled) condition after the form has been displayed you may have to callrow.evaluateHidden()
to force Eureka to reevaluate the new condition.
Seethis FAQ sectionfor more info.
For sections this works just the same. That means we can set up sectionhidden
property to show/hide it dynamically.
To disable rows, each row has andisabled
variable which is also an optionalCondition
type property. This variable also works the same as thehidden
variable so that it requires the rows to have a tag.
Note that if you want to disable a row permanently you can also setdisabled
variable totrue
.
To display a list of options, Eureka includes a special section calledSelectableSection
.
When creating one you need to pass the type of row to use in the options and theselectionType
.
TheselectionType
is an enum which can be eithermultipleSelection
orsingleSelection(enableDeselection: Bool)
where theenableDeselection
parameter determines if the selected rows can be deselected or not.
form+++SelectableSection<ListCheckRow<String>>("Where do you live",selectionType:.singleSelection(enableDeselection:true))
letcontinents=["Africa","Antarctica","Asia","Australia","Europe","North America","South America"]
foroptionin continents{
form.last!<<<ListCheckRow<String>(option){listRowin
listRow.title=option
listRow.selectableValue=option
listRow.value=nil
}
}
To create such a section you have to create a row that conforms theSelectableRowType
protocol.
publicprotocolSelectableRowType:RowType{
varselectableValue:Value?{getset}
}
ThisselectableValue
is where the value of the row will be permanently stored. Thevalue
variable will be used to determine if the row is selected or not, being 'selectableValue' if selected or nil otherwise.
Eureka includes theListCheckRow
which is used for example. In the custom rows of the Examples project you can also find theImageCheckRow
.
To easily get the selected row/s of aSelectableSection
there are two methods:selectedRow()
andselectedRows()
which can be called to get the selected row in case it is aSingleSelection
section or all the selected rows if it is aMultipleSelection
section.
Additionally you can setup list of options to be grouped by sections using following properties ofSelectorViewController
:
-
sectionKeyForValue
- a closure that should return key for particular row value. This key is later used to break options by sections. -
sectionHeaderTitleForKey
- a closure that returns header title for a section for particular key. By default returns the key itself. -
sectionFooterTitleForKey
- a closure that returns footer title for a section for particular key.
Eureka supports multiple values for a certain field (such as telephone numbers in a contact) by using Multivalued sections. It allows us to easily create insertable, deletable and reorderable sections.
In order to create a multivalued section we have to useMultivaluedSection
type instead of the regularSection
type.MultivaluedSection
extendsSection
and has some additional properties to configure multivalued section behavior.
let's dive into a code example...
form+++
MultivaluedSection(multivaluedOptions:[.Reorder,.Insert,.Delete],
header:"Multivalued TextField",
footer:".Insert adds a 'Add Item' (Add New Tag) button row as last cell."){
$0.addButtonProvider={sectionin
returnButtonRow(){
$0.title="Add New Tag"
}
}
$0.multivaluedRowToInsertAt={indexin
returnNameRow(){
$0.placeholder="Tag Name"
}
}
$0<<<NameRow(){
$0.placeholder="Tag Name"
}
}
Previous code snippet shows how to create a multivalued section. In this case we want to insert, delete and reorder rows as multivaluedOptions argument indicates.
addButtonProvider
allows us to customize the button row which inserts a new row when tapped andmultivaluedOptions
contains.Insert
value.
multivaluedRowToInsertAt
closure property is called by Eureka each time a new row needs to be inserted. In order to provide the row to add into multivalued section we should set this property. Eureka passes the index as closure parameter. Notice that we can return any kind of row, even custom rows, even though in most cases multivalued section rows are of the same type.
Eureka automatically adds a button row when we create a insertable multivalued section. We can customize how the this button row looks like as we explained before.showInsertIconInAddButton
property indicates if plus button (insert style) should appear in the left of the button, true by default.
There are some considerations we need to have in mind when creating insertable sections. Any row added to the insertable multivalued section should be placed above the row that Eureka automatically adds to insert new rows. This can be easily achieved by adding these additional rows to the section from inside the section's initializer closure (last parameter of section initializer) so then Eureka adds the adds insert button at the end of the section.
By default Eureka will set the tableView'sisEditing
to true only if there is a MultivaluedSection in the form. This will be done inviewWillAppear
the first time a form is presented.
For more information on how to use multivalued sections please take a look at Eureka example project which contains several usage examples.
If you want to use an add button which is not aButtonRow
then you can useGenericMultivaluedSection<AddButtonType>
,whereAddButtonType
is the type of the row you want to use as add button. This is useful if you want to use a custom row to change the UI of the button.
Example:
GenericMultivaluedSection<LabelRow>(multivaluedOptions:[.Reorder,.Insert,.Delete],{
$0.addButtonProvider={sectionin
returnLabelRow(){
$0.title="A Label row as add button"
}
}
//...
}
Eureka 2.0.0 introduces the much requested built-in validations feature.
A row has a collection ofRules
and a specific configuration that determines when validation rules should be evaluated.
There are some rules provided by default, but you can also create new ones on your own.
The provided rules are:
- RuleRequired
- RuleEmail
- RuleURL
- RuleGreaterThan, RuleGreaterOrEqualThan, RuleSmallerThan, RuleSmallerOrEqualThan
- RuleMinLength, RuleMaxLength
- RuleClosure
Let's see how to set up the validation rules.
overridefuncviewDidLoad(){
super.viewDidLoad()
form
+++Section(header:"Required Rule",footer:"Options: Validates on change")
<<<TextRow(){
$0.title="Required Rule"
$0.add(rule:RuleRequired())
// This could also have been achieved using a closure that returns nil if valid, or a ValidationError otherwise.
/*
let ruleRequiredViaClosure = RuleClosure<String> { rowValue in
return (rowValue == nil || rowValue!.isEmpty)? ValidationError(msg: "Field required!" ): nil
}
$0.add(rule: ruleRequiredViaClosure)
*/
$0.validationOptions=.validatesOnChange
}
.cellUpdate{cell,rowin
if!row.isValid{
cell.titleLabel?.textColor=.systemRed
}
}
+++Section(header:"Email Rule, Required Rule",footer:"Options: Validates on change after blurred")
<<<TextRow(){
$0.title="Email Rule"
$0.add(rule:RuleRequired())
$0.add(rule:RuleEmail())
$0.validationOptions=.validatesOnChangeAfterBlurred
}
.cellUpdate{cell,rowin
if!row.isValid{
cell.titleLabel?.textColor=.systemRed
}
}
As you can see in the previous code snippet we can set up as many rules as we want in a row by invoking row'sadd(rule:)
function.
Row also providesfunc remove(ruleWithIdentifier identifier: String)
to remove a rule. In order to use it we must assign an id to the rule after creating it.
Sometimes the collection of rules we want to use on a row is the same we want to use on many other rows. In this case we can set up all validation rules using aRuleSet
which is a collection of validation rules.
varrules=RuleSet<String>()
rules.add(rule:RuleRequired())
rules.add(rule:RuleEmail())
letrow=TextRow(){
$0.title="Email Rule"
$0.add(ruleSet:rules)
$0.validationOptions=.validatesOnChangeAfterBlurred
}
Eureka allows us to specify when validation rules should be evaluated. We can do it by setting upvalidationOptions
row's property, which can have the following values:
.validatesOnChange
- Validates whenever a row value changes..validatesOnBlur
- (Default value) validates right after the cell resigns first responder. Not applicable for all rows..validatesOnChangeAfterBlurred
- Validates whenever the row value changes after it resigns first responder for the first time..validatesOnDemand
- We should manually validate the row or form by invokingvalidate()
method.
If you want to validate the entire form (all the rows) you can manually invoke Formvalidate()
method.
Each row has thevalidationErrors
property that can be used to retrieve all validation errors. This property just holds the validation error list of the latest row validation execution, which means it doesn't evaluate the validation rules of the row.
As expected, the Rules must use the same types as the Row object. Be extra careful to check the row type used. You might see a compiler error ( "Incorrect arugment label in call (have 'rule:' expected 'ruleSet:')" that is not pointing to the problem when mi xing types.
By using swipe actions we can define multipleleadingSwipe
andtrailingSwipe
actions per row. As swipe actions depend on iOS system features,leadingSwipe
is available on iOS 11.0+ only.
Let's see how to define swipe actions.
letrow=TextRow(){
letdeleteAction=SwipeAction(
style:.destructive,
title:"Delete",
handler:{(action,row,completionHandler)in
//add your code here.
//make sure you call the completionHandler once done.
completionHandler?(true)
})
deleteAction.image=UIImage(named:"icon-trash")
$0.trailingSwipe.actions=[deleteAction]
$0.trailingSwipe.performsFirstActionWithFullSwipe=true
//please be aware: `leadingSwipe` is only available on iOS 11+ only
letinfoAction=SwipeAction(
style:.normal,
title:"Info",
handler:{(action,row,completionHandler)in
//add your code here.
//make sure you call the completionHandler once done.
completionHandler?(true)
})
infoAction.actionBackgroundColor=.blue
infoAction.image=UIImage(named:"icon-info")
$0.leadingSwipe.actions=[infoAction]
$0.leadingSwipe.performsFirstActionWithFullSwipe=true
}
Swipe Actions needtableView.isEditing
be set tofalse
.Eureka will set this totrue
if there is a MultivaluedSection in the form (in theviewWillAppear
).
If you have both MultivaluedSections and swipe actions in the same form you should setisEditing
according to your needs.
It is very common that you need a row that is different from those included in Eureka. If this is the case you will have to create your own row but this should not be difficult. You can readthis tutorial on how to create custom rowsto get started. You might also want to have a look atEurekaCommunitywhich includes some extra rows ready to be added to Eureka.
To create a row with custom behaviour and appearance you'll probably want to create subclasses ofRow
andCell
.
Remember thatRow
is the abstraction Eureka uses, while theCell
is the actualUITableViewCell
in charge of the view.
As theRow
contains theCell
,bothRow
andCell
must be defined for the samevaluetype.
// Custom Cell with value type: Bool
// The cell is defined using a.xib, so we can set outlets:)
publicclassCustomCell:Cell<Bool>,CellType{
@IBOutletweakvarswitchControl:UISwitch!
@IBOutletweakvarlabel:UILabel!
publicoverridefuncsetup(){
super.setup()
switchControl.addTarget(self,action:#selector(CustomCell.switchValueChanged),for:.valueChanged)
}
funcswitchValueChanged(){
row.value=switchControl.on
row.updateCell()// Re-draws the cell which calls 'update' bellow
}
publicoverridefuncupdate(){
super.update()
backgroundColor=(row.value??false)?.white:.black
}
}
// The custom Row also has the cell: CustomCell and its correspond value
publicfinalclassCustomRow:Row<CustomCell>,RowType{
requiredpublicinit(tag:String?){
super.init(tag:tag)
// We set the cellProvider to load the.xib corresponding to our cell
cellProvider=CellProvider<CustomCell>(nibName:"CustomCell")
}
}
Custom rows need to subclass `Row` and conform to `RowType` protocol. Custom cells need to subclass `Cell` and conform to `CellType` protocol.
Just like the callbacks cellSetup and CellUpdate, theCell
has the setup and update methods where you can customize it.
An inline row is a specific type of row that shows dynamically a row below it, normally an inline row changes between an expanded and collapsed mode whenever the row is tapped.
So to create an inline row we need 2 rows, the row that is "always" visible and the row that will expand/collapse.
Another requirement is that the value type of these 2 rows must be the same. This means if one row holds aString
value then the other must have aString
value too.
Once we have these 2 rows, we should make the top row type conform toInlineRowType
.
This protocol requires you to define anInlineRow
typealias and asetupInlineRow
function.
TheInlineRow
type will be the type of the row that will expand/collapse.
Take this as an example:
classPickerInlineRow<T>:Row<PickerInlineCell<T>>whereT:Equatable{
publictypealiasInlineRow=PickerRow<T>
openvaroptions=[T]()
requiredpublicinit(tag:String?){
super.init(tag:tag)
}
publicfuncsetupInlineRow(_ inlineRow:InlineRow){
inlineRow.options=self.options
inlineRow.displayValueFor=self.displayValueFor
inlineRow.cell.height={UITableViewAutomaticDimension}
}
}
TheInlineRowType
will also add some methods to your inline row:
funcexpandInlineRow()
funccollapseInlineRow()
functoggleInlineRow()
These methods should work fine but should you want to override them keep in mind that it istoggleInlineRow
that has to callexpandInlineRow
andcollapseInlineRow
.
Finally you must invoketoggleInlineRow()
when the row is selected, for example overridingcustomDidSelect
:
publicoverridefunccustomDidSelect(){
super.customDidSelect()
if!isDisabled{
toggleInlineRow()
}
}
Note:A Presenter row is a row that presents a new UIViewController.
To create a custom Presenter row you must create a class that conforms thePresenterRowType
protocol. It is highly recommended to subclassSelectorRow
as it does conform to that protocol and adds other useful functionality.
The PresenterRowType protocol is defined as follows:
publicprotocolPresenterRowType:TypedRowType{
associatedtypePresentedControllerType:UIViewController,TypedRowControllerType
/// Defines how the view controller will be presented, pushed, etc.
varpresentationMode:PresentationMode<PresentedControllerType>?{getset}
/// Will be called before the presentation occurs.
varonPresentCallback:((FormViewController,PresentedControllerType)->Void)?{getset}
}
The onPresentCallback will be called when the row is about to present another view controller. This is done in theSelectorRow
so if you do not subclass it you will have to call it yourself.
ThepresentationMode
is what defines how the controller is presented and which controller is presented. This presentation can be using a Segue identifier, a segue class, presenting a controller modally or pushing to a specific view controller. For example a CustomPushRow can be defined like this:
Let's see an example..
/// Generic row type where a user must select a value among several options.
openclassSelectorRow<Cell:CellType>:OptionsRow<Cell>,PresenterRowTypewhereCell:BaseCell{
/// Defines how the view controller will be presented, pushed, etc.
openvarpresentationMode:PresentationMode<SelectorViewController<SelectorRow<Cell>>>?
/// Will be called before the presentation occurs.
openvaronPresentCallback:((FormViewController,SelectorViewController<SelectorRow<Cell>>)->Void)?
requiredpublicinit(tag:String?){
super.init(tag:tag)
}
/**
Extends `didSelect` method
*/
openoverridefunccustomDidSelect(){
super.customDidSelect()
guardletpresentationMode=presentationMode,!isDisabledelse{return}
ifletcontroller=presentationMode.makeController(){
controller.row=self
controller.title=selectorTitle??controller.title
onPresentCallback?(cell.formViewController()!,controller)
presentationMode.present(controller,row:self,presentingController:self.cell.formViewController()!)
}else{
presentationMode.present(nil,row:self,presentingController:self.cell.formViewController()!)
}
}
/**
Prepares the pushed row setting its title and completion callback.
*/
openoverridefuncprepare(for segue:UIStoryboardSegue){
super.prepare(for:segue)
guardletrowVC=segue.destinationasAnyas?SelectorViewController<SelectorRow<Cell>>else{return}
rowVC.title=selectorTitle??rowVC.title
rowVC.onDismissCallback=presentationMode?.onDismissCallback??rowVC.onDismissCallback
onPresentCallback?(cell.formViewController()!,rowVC)
rowVC.row=self
}
}
// SelectorRow conforms to PresenterRowType
publicfinalclassCustomPushRow<T:Equatable>:SelectorRow<PushSelectorCell<T>>,RowType{
publicrequiredinit(tag:String?){
super.init(tag:tag)
presentationMode=.show(controllerProvider:ControllerProvider.callback{
returnSelectorViewController<T>(){_in}
},onDismiss:{vcin
_=vc.navigationController?.popViewController(animated:true)
})
}
}
Sometimes we want to change the UI look of one of our rows but without changing the row type and all the logic associated to one row. There is currently one way to do thisif you are using cells that are instantiated from nib files.Currently, none of Eureka's core rows are instantiated from nib files but some of the custom rows inEurekaCommunityare, in particular thePostalAddressRowwhich was moved there.
What you have to do is:
- Create a nib file containing the cell you want to create.
- Then set the class of the cell to be the existing cell you want to modify (if you want to change something more apart from pure UI then you should subclass that cell). Make sure the module of that class is correctly set
- Connect the outlets to your class
- Tell your row to use the new nib file. This is done by setting the
cellProvider
variable to use this nib. You should do this in the initialiser, either in each concrete instantiation or using thedefaultRowInitializer
.For example:
<<<PostalAddressRow(){
$0.cellProvider=CellProvider<PostalAddressCell>(nibName:"CustomNib",bundle:Bundle.main)
}
You could also create a new row for this. In that case try to inherit from the same superclass as the row you want to change to inherit its logic.
There are some things to consider when you do this:
- If you want to see an example have a look at thePostalAddressRowor theCreditCardRowwhich have use a custom nib file in their examples.
- If you get an error saying
Unknown class <YOUR_CLASS_NAME> in Interface Builder file
,it might be that you have to instantiate that new type somewhere in your code to load it in the runtime. Callinglet t = YourClass.self
helped in my case.
Label Row |
Button Row |
Check Row |
Switch Row |
Slider Row |
Stepper Row |
Text Area Row |
These 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 ZipCodeRow |
|
All of theFieldRow
subtypes above have aformatter
property of typeNSFormatter
which can be set to determine how that row's value should be displayed. A custom formatter for numbers with two digits after the decimal mark is included with Eureka (DecimalFormatter
). The Example project also contains aCurrencyFormatter
which displays a number as currency according to the user's locale.
By default, setting a row'sformatter
only affects how a value is displayed when it is not being edited. To also format the value while the row is being edited, setuseFormatterDuringInput
totrue
when initializing the row. Formatting the value as it is being edited may require updating the cursor position and Eureka provides the following protocol that your formatter should conform to in order to handle cursor position:
publicprotocolFormatterProtocol{
funcgetNewPosition(forPosition forPosition:UITextPosition,inTextInput textInput:UITextInput,oldValue:String?,newValue:String?)->UITextPosition
}
Additionally,FieldRow
subtypes have auseFormatterOnDidBeginEditing
property. When using aDecimalRow
with a formatter that allows decimal values and conforms to the user's locale (e.g.DecimalFormatter
), ifuseFormatterDuringInput
isfalse
,useFormatterOnDidBeginEditing
must be set totrue
so that the decimal mark in the value being edited matches the decimal mark on the keyboard.
Date Rows hold a Date and allow us to set up a new value through UIDatePicker control. The mode of the UIDatePicker and the way how the date picker view is shown is what changes between them.
Date Row
Picker shown in the keyboard. |
Date Row (Inline)
The row expands. |
Date Row (Picker)
The picker is always visible. |
With those 3 styles (Normal, Inline & Picker), Eureka includes:
- DateRow
- TimeRow
- DateTimeRow
- CountDownRow
These are rows with a list of options associated from which the user must choose.
<<<ActionSheetRow<String>(){
$0.title="ActionSheetRow"
$0.selectorTitle="Pick a number"
$0.options=["One","Two","Three"]
$0.value="Two"// initially selected
}
Segmented Row |
Segmented Row (w/Title) |
Picker Row Presents options of a generic type through a picker view (There is also Picker Inline Row) |
Let us know about it, we would be glad to mention it here.:)
- LocationRow(Included as custom row in the example project)
CocoaPodsis a dependency manager for Cocoa projects.
Specify Eureka into your project'sPodfile
:
source'https://github /CocoaPods/Specs.git'
platform:ios,'9.0'
use_frameworks!
pod'Eureka'
Then run the following command:
$ pod install
Swift Package Manageris a tool for managing the distribution of Swift code.
After you set up yourPackage.swift
manifest file, you can add Eureka as a dependency by adding it to the dependencies value of yourPackage.swift
.
dependencies: [ .package(url: "https://github /xmartlabs/Eureka.git",from:" 5.5.0 ") ]
Carthageis a simple, decentralized dependency manager for Cocoa.
Specify Eureka into your project'sCartfile
:
github "xmartlabs/Eureka" ~> 5.5
- Clone Eureka as a gitsubmoduleby running the following command from your project root git folder.
$ git submodule add https://github /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!
- If youwant to contributeplease feel free tosubmit pull requests.
- If youhave a feature requestpleaseopen an issue.
- If youfound a bugcheck older issues before submitting an issue.
- If youneed helpor would like toask general question,useStackOverflow.(Tag
eureka-forms
).
Before contribute check theCONTRIBUTINGfile for more info.
If you useEurekain your app We would love to hear about it! Drop us a line ontwitter.
Every row has the following property:
/// Block variable used to get the String that should be displayed for the value of this row.
publicvardisplayValueFor:((T?)->String?)?={
return$0.map{String(describing:$0)}
}
You can setdisplayValueFor
according the string value you want to display.
We can get a particular row by invoking any of the following functions exposed by theForm
class:
publicfuncrowBy<T:Equatable>(tag:String)->RowOf<T>?
publicfuncrowBy<Row:RowType>(tag:String)->Row?
publicfuncrowBy(tag:String)->BaseRow?
For instance:
letdateRow:DateRow?=form.rowBy(tag:"dateRowTag")
letlabelRow:LabelRow?=form.rowBy(tag:"labelRowTag")
letdateRow2:Row<DateCell>?=form.rowBy(tag:"dateRowTag")
letlabelRow2:BaseRow?=form.rowBy(tag:"labelRowTag")
letsection:Section?=form.sectionBy(tag:"sectionTag")
InvokingsetValues(values: [String: Any?])
which is exposed byForm
class.
For example:
form.setValues(["IntRowTag":8,"TextRowTag":"Hello world!","PushRowTag":Company(name:"Xmartlabs")])
Where"IntRowTag"
,"TextRowTag"
,"PushRowTag"
are row tags (each one uniquely identifies a row) and8
,"Hello world!"
,Company(name: "Xmartlabs" )
are the corresponding row value to assign.
The value type of a row must match with the value type of the corresponding dictionary value otherwise nil will be assigned.
If the form was already displayed we have to reload the visible rows either by reloading the table viewtableView.reloadData()
or invokingupdateCell()
to each visible row.
Row does not update after changing hidden or disabled condition
After setting a condition, this condition is not automatically evaluated. If you want it to do so immediately you can call.evaluateHidden()
or.evaluateDisabled()
.
This functions are just called when a row is added to the form and when a row it depends on changes. If the condition is changed when the row is being displayed then it must be reevaluated manually.
Look at thisissue.
- Set up a new header/footer data....
section.header=HeaderFooterView(title:"Header title\(variable)")// use String interpolation
//or
varheader=HeaderFooterView<UIView>(.class)// most flexible way to set up a header using any view type
header.height={60}// height can be calculated
header.onSetupView={view,sectionin// each time the view is about to be displayed onSetupView is invoked.
view.backgroundColor=.orange
}
section.header=header
- Reload the Section to perform the changes
section.reload()
selectableRowSetup
,selectableRowCellUpdate
andselectableRowCellSetup
properties are provided to be able to customize SelectorViewController and MultipleSelectorViewController selectable cells.
letrow=PushRow<Emoji>(){
$0.title="PushRow"
$0.options=[💁🏻,🍐,👦🏼,🐗,🐼,🐻]
$0.value=👦🏼
$0.selectorTitle="Choose an Emoji!"
}.onPresent{from,toin
to.dismissOnSelection=false
to.dismissOnChange=false
to.selectableRowSetup={rowin
row.cellProvider=CellProvider<ListCheckCell<Emoji>>(nibName:"EmojiCell",bundle:Bundle.main)
}
to.selectableRowCellUpdate={cell,rowin
cell.textLabel?.text="Text"+row.selectableValue!// customization
cell.detailTextLabel?.text="Detail"+row.selectableValue!
}
}
As we've saidForm
andSection
types conform toMutableCollection
andRangeReplaceableCollection
.A Form is a collection of Sections and a Section is a collection of Rows.
RangeReplaceableCollection
protocol extension provides many useful methods to modify collection.
extensionRangeReplaceableCollection{
publicmutatingfuncappend(_ newElement:Self.Element)
publicmutatingfuncappend<S>(contentsOf newElements:S)whereS:Sequence,Self.Element==S.Element
publicmutatingfuncinsert(_ newElement:Self.Element,at i:Self.Index)
publicmutatingfuncinsert<S>(contentsOf newElements:S,at i:Self.Index)whereS:Collection,Self.Element==S.Element
publicmutatingfuncremove(at i:Self.Index)->Self.Element
publicmutatingfuncremoveSubrange(_ bounds:Range<Self.Index>)
publicmutatingfuncremoveFirst(_ n:Int)
publicmutatingfuncremoveFirst()->Self.Element
publicmutatingfuncremoveAll(keepingCapacity keepCapacity:Bool)
publicmutatingfuncreserveCapacity(_ n:Self.IndexDistance)
}
These methods are used internally to implement the custom operators as shown bellow:
publicfunc+++(left:Form,right:Section)->Form{
left.append(right)
returnleft
}
publicfunc+=<C:Collection>(inout lhs:Form,rhs:C)whereC.Element==Section{
lhs.append(contentsOf:rhs)
}
publicfunc<<<(left:Section,right:BaseRow)->Section{
left.append(right)
returnleft
}
publicfunc+=<C:Collection>(inout lhs:Section,rhs:C)whereC.Element==BaseRow{
lhs.append(contentsOf:rhs)
}
You can see how the rest of custom operators are implementedhere.
It's up to you to decide if you want to use Eureka custom operators or not.
The form is always displayed in aUITableView
.You can set up your view controller in a storyboard and add a UITableView where you want it to be and then connect the outlet to FormViewController'stableView
variable. This allows you to define a custom frame (possibly with constraints) for your form.
All of this can also be done by programmatically changing frame, margins, etc. of thetableView
of your FormViewController.
So we can make Eureka even better!
This can be found in theCHANGELOG.mdfile.