RxSwift and Layout
I recently found out about Layout which is a declarative framework for managing views and layouts in iOS using XML. It’s open source and maintained by Schibsted Media Group. The framework looks promising and I recommend you to try it out for yourself.
I will not describe the framework in detail because it’s already well documented on the project page at Github. In addition to declaring views and layouts the framework also supports state variables, expressions inside XML-attributes and live reloading views in the simulator without having to recompile the application.
I’ll give you an idea on how it may look like when using Layout.
A typical scenario is to have a button disabled until the user toggles a switch to accept the terms and conditions for your application.
Lets use aUISwitch
to toggle a state variable which in turn enables/disables a create account button.
- The
termsChanged
function will be called when theUISwitch
value changes - The callback function updates the
canCreateAccount
state variable - The expression is evaluated in
isEnabled
and the button will be either enabled or disabled - The expression is evaluated in
backgroundColor
and updates the button’s background color to either red or green
I was curious to find out how well Layout integrates with RxSwift. It didn’t take too long to conclude that they both played well together.
Basically, there’re two options:
- Using Layout’s outlet support and get a handle to any UI component created inside the XML files
- Use state variables
The first options is pretty much like when using Storyboards. You’ll have a reference to the UI component in your view controller. The second option is to use state variables, preferable, in combination with RxSwift’sbind(to: )
instead of subscribe(onNext: {})
to update state changes.
Creating a Reactive
extension with a custom binding was straight forward, just add a function named state
with one parameter (the name of the state variable) and return the Binder
.
So instead of having the termsChanged
callback, we use an outlet to the UISwitch
and bind the state variable.
That’s all there is to it!
Personally, I find the combination of RxSwift and Layout really neat. Declarative programming makes me much more productive. A big bonus is the support for live reloading of views which boosts the productive a lot.
Thanks for reading.