Code Monkey home page Code Monkey logo

simpletwowaybindingios's Introduction

update: 08/24/2019

This repository was created for demonstration purpose rather than for consumption. However, given the feedback and usage of this repository, I will start maintaining it here-on and priortize fixing/implementing raised issues.

SimpleTwoWayBinding for iOS

Version License Platform

The Need

MVVM? why not MVC that Apple recommends? Android does MVP great right? How about the cool VIPER pattern? I believe great efforts have already been put to explain what each pattern brings to the table and so the idea here is not to add to the debate but merely build on top of the opinion I have already formed: MVVM is the way to go.

As a quick primer to what MVVM is, it is a design pattern whereby the ViewModel mediates between a data providing Model and View which displays the data provided like shown below:

mvvm diag

in iOS, View is essentially a ViewController and ViewModel is an object (a structure) which provides exact data for the view to render.

This provides a loosely coupled architecture which is maintainable ( very thin view controllers ) and testable (ViewModel abstracts out the UI and hence is easily testable)

There is still a caveat though: classic MVVM allows for single responsibility principle easily (and beautifully) in case of models as domain models. However, in case of anaemic models ( which is generally the case when you have well written REST APIs), one would also need another Mediator or Presenter which facilitates data and navigation flow.

Now, View Model has responsibility to update View as well as get updates from View regarding the changes made by the user. This can be achieved by minimum code using bi-directional data binding. But โ€ฆ iOS has no two way binding mechanism available out of the box!

Luckily we have reactive libraries like RxSwift, RxCocoa but they are too heavy considering two way binding is a very tiny part of the Reactive Programming paradigm. SimpleTwoWayBinding strives to provide just two way binding, in a simple unassuming way!

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Creating ViewModel

import SimpleTwoWayBinding

struct FormViewModel {
    let name: Observable<String> = Observable()
    let companyName: Observable<String> = Observable()
    let yearsOfExperience: Observable<Double> = Observable()
    let isCurrentEmployer: Observable<Bool> = Observable(false)
    let approxSalary: Observable<Float> = Observable()
    let comments: Observable<String> = Observable()
}

The properties you want to be "bindable" to the View should be declared as Observable.

Binding to ViewController

class ViewController: UIViewController {

    @IBOutlet weak var nameField: UITextField!
    @IBOutlet weak var companyField: UITextField!
    @IBOutlet weak var isCurrentEmployerSwitch: UISwitch!
    @IBOutlet weak var yearsOfExperienceStepper: UIStepper!
    @IBOutlet weak var salaryRangeSlider: UISlider!
    @IBOutlet weak var selectedSalaryRangeLabel: UILabel!
    @IBOutlet weak var selectedYearsOfExperienceLabel: UILabel!
    
    var viewModel: FormViewModel!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.title = "Survey Form"
        setupBindings()
    }
    
    func setupBindings() {
        nameField.bind(with: viewModel.name)
        companyField.bind(with: viewModel.companyName)
        isCurrentEmployerSwitch.bind(with: viewModel.isCurrentEmployer)
        yearsOfExperienceStepper.bind(with: viewModel.yearsOfExperience)
        salaryRangeSlider.bind(with: viewModel.approxSalary)
      
        selectedSalaryRangeLabel.observe(for: viewModel.approxSalary) {
            [unowned self](_) in
            self.selectedSalaryRangeLabel.text =
                self.viewModel.getSalaryString()
        }
        
        selectedYearsOfExperienceLabel.observe(for: viewModel.yearsOfExperience) {
            [unowned self](_) in
            self.selectedYearsOfExperienceLabel.text =
                self.viewModel.getExperienceString()
        }
    }
}

The bind method on the UIControl orchestrates the two way binding with the Observable. That's all code that is needed to get the form working. See below screen shot.

working sample

Installation

SimpleTwoWayBinding is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'SimpleTwoWayBinding'

Author

Manish Katoch, [email protected]

License

SimpleTwoWayBinding is available under the MIT license. See the LICENSE file for more info.

simpletwowaybindingios's People

Contributors

fweez avatar jeremy-doneghue avatar manishkkatoch avatar meguid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simpletwowaybindingios's Issues

Unbind a control

Probably a stupid question ... but how do you un-bind a control ?
I added the binding to a view in a UITableViewCell and I'm having some troubles as other cells are reacting to the bind when my cell is off screen. While on-screen, all's good, updates realtime.
I think the way to fix that would be to unbind on didEndDisplayingCell.

UITextField and UITextView don't behave well with some unicode

The updateValue methods in the UITextField and UITextView appear to be tickling a UIKit bug, causing the cursor to unexpectedly jump to the end of the text field while editing.

  1. In the example app, enter some text with a double-width unicode character, such as ๐Ÿ• , in the middle. For instance, I entered "Ryan ๐Ÿ• Forsythe".
  2. Move the cursor back to the middle of the text. For instance, I moved the cursor to just after the "n" character.
  3. Type any character or hit the backspace
  4. That character appears at the cursor, but then the cursor immediately jumps to the end of the text field.

This repro is for UITextField, but we're seeing the same issue in UITextView. If the whole text field is single-width characters (the ASCII region of unicode works for this) this bug doesn't happen, so I assume this is actually a bug in UIKit. The fix is pretty easy, though. I've forked and made the change, and will send a PR referencing this issue.

issue on bindable func

_self.addTarget(Selector, action: Selector{ [weak self] in self?.valueChanged() }, for: [.editingChanged, .valueChanged])
it gives "Cannot convert value of type '() -> ()?' to expected argument type 'String' " error

Initial Model value not shown on UIControls

Hello! Thank you for creating this library and explaining TwoWayBinding.
I found something is missing, or I must be doing something wrong.
What I am expecting it to do?
When a model's parameter and a UIControl is bound, I expect the UIControl to display the initial value of the bound parameter when the control is loaded. Later, when the control updates its text, the changes should be reflected in the bound model's parameter.
What is missing?
The second part, model's parameter is being updated based on control's input is working effortlessly. But, the first part is not working or I must be missing something.
What I tried?
In the example code, when I update FormViewModel to modify the name parameter to hold the value 'John Doe', let name: Observable<String> = Observable("John Doe") I expect the nameField of ViewController to load with text 'John Doe'.
This update doesn't happen unless I update to function bind in Observable to this,

public func bind(observer: @escaping Observer) { self.observers.append(observer) if let value = value { notifyObservers(value) } }

That is when the binding is happening let the observer take the current value if it has any.

I would like to know what I am missing here. Thanks in advance ๐Ÿ‘

No exact matches in call to initializer

In the file Bindable, xcode is showing error at line

_self.addTarget(Selector, action: Selector{ [weak self] in self?.valueChanged() }, for: [.editingChanged, .valueChanged])

Where is the model?

In your examples i see only a viewModel with all properties... how can i declare a model class in view model and be able to bind their properties?

class PersonModel {
var name: String?
var surname: String?
}


class PersonViewModel {
var person:Person!
var completeName{
return person.name + " " + person.surname
}
}

class ViewController: UIViewController {
.
.
.

var personViewModel:PersonViewModel!
.
.
.
personViewModel.completeName = personCompleteNameTextField.text // ???
}

How can i bind (change) per model (Person) name or surname from viewModel?

textField.observe has issues with cell reuse

If I have multiple text fields in a table observing changes to a model property, then as the cells are reused they start observing multiple properties. This can be fixed by checking that the observable value returned matches the model property, but it would be better to clear observables when a cell is reused (and as far as I know you can only add obervables).
For the example below, changing pickerTwo value will sometimes also update rowOne as it has previously been observing rowTwo (under cell reuse rules)

case .rowOne:
    cell.textField.observe(for: vModel.propertyOne) { (prop1) in
        //hack way of ensuring observable is right one (as cannot remove "observe" for cell reuse)
        if prop1 == vModel.propertyOne.value {
            cell.textField.text = getPropOneValue()
        }
    }
    cell.textField.text = vModel.getPropOneValue()
    cell.textField.inputView = pickerOne
case .rowTwo:
    cell.textField.observe(for: vModel.propertyTwo) { (prop2) in
        if prop2 == vModel.propertyTwo.value {
            cell.textField.text = getPropTwoValue()
        }
    }
    cell.textField.text = vModel.getPropTwoValue()
    cell.textField.inputView = pickerTwo

Observable doesn't support optional ObservedType

Hey, right now this library has Observable which might support on theory observing optional types. The problem is that when the value is being set, you have this check:

    public var value: ObservedType? {
        didSet {
            if let value = value {
                notifyObservers(value)
            }
        }
    }

That doesn't allow the observing instance to react to the "cleanup" of this model.
For example if ObservedType = UIImage, and I want to clean up the image from the UIImageView:

viewModel.thumbnailImage.bind { [weak self] _ , image in
            self?.imageView.image = image
        }

This code will not be invoked for a nil value.

Do you have any plans to support setting nil value to Observable?

Memory Leak?

I noticed that there's no support for removing an observer, and observers are held in an array.

That means that over time, as more and more views are used, the array of observers fills up with more and more items - hopefully the blocks used did not reference anything big, using weak self and so on should keep it small.

Still, I need to be able to remove observers.

Then observers could be added / removed when views willShow / willHide

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.