-2

Actually someone asked me this question and I'm also interested to know, that how to bind data to a UI element directly. I know UITableview have Datasource property but it doesn't bind data directly. We have to use its protocol methods to bind data in code.

Is there any other way from which we can bind data to the View or is this possible or not? In .Net gridview we can bind data from database to gridview directly.

Rakesh
  • 3,370
  • 2
  • 23
  • 41
Rahul Shirphule
  • 989
  • 3
  • 14
  • 36

2 Answers2

1

Update: If you mean synchronizing backing data with UI elements then read the last paragraph.

It would be against the recommended MVC pattern to bind data directly to the view if I understand your question correctly. Check the below links for more info.

Why MVC?

[Why MVC instead of good old ASP.NET? Still not grasping why I should go this route?][2]

However if you do want to bind data directly, there is nothing stopping you from it, even though it might be a bad idea unless the use case is trivial. For e.g. UITableViews are available with static cells. And if a pre-built UI element doesn't have a provision to bind data (don't know of any) to it directly, you could make a similar UI element that serves the purpose.

However it would take way more effort to build such and element than to supply data to it the existing one through preferred methods.

By binding data directly, if you mean supplying the data through interface builder, then you are out of luck. In Cocoa (for OS X application development), there is something called Bindings that help you synchronize your UI elements with the backing data. However in iOS there isn't such a thing. But you could use Key - Value - Observing to achieve this to some extent. Also why iOS might not have such bindings may be partially answered here: Is there any technical/conceptual reason why iOS does not support Cocoa Bindings?. And check this if you have a need on such functionality: Is there any data binding mechanism available for iOS?

Community
  • 1
  • 1
Rakesh
  • 3,370
  • 2
  • 23
  • 41
0

While it isn't exactly binding, I have used didSet property observers to update UI elements like this:

var label: UILabel?

var labelText = "Change me." {
    didSet {
        label?.text = labelText
    }
}

That assumes you have initialized label somewhere appropriately. I believe that is the closest you can get in iOS.

Aaron Rasmussen
  • 13,082
  • 3
  • 42
  • 43