How to bind value of UILabel to an instance variable?

假装没事ソ 提交于 2020-01-04 18:14:52

问题


I am a complete newbie to mac/objective-c. My question is: I wonder if it's possible to bind a UILabel text to a variable, while not having to manually set the text when value change.

For example, on Mac OS, when I open a new Finder window and delete a file, then the global free space in the taskbar is changing. And that value also change in all the "finder" that are open.

How can I replicate such behavior using Objective-c, either on Mac or for iPhone ? I was thinking about UILabel, but I couldn't find a way different from manually set each UILabel.

thanks Leonardo


回答1:


The current version of iPhone OS (3.1) does not support bindings (such as you would find in desktop Cocoa). For the time being, you will need to write the controller glue manually to keep the UI in sync with your model.

Specifically, you would add an IBAction method in your controller, and connect the UILabel to call it when the contents changes.

This question has been covered before also:

  • Bindings using Interface Builder (for iPhone apps)

On the Mac, you would use Key-Value Coding (KVC) and bind the label to an object controller in IB. The bindings documentation covers this in quite some detail:

  • http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaBindings/CocoaBindings.html



回答2:


You will need to research the following:

  1. Notifications Notifications

and/or

  1. Key Value Coding KVC

Notifications will allow you to setup up automatic notifications of changes to let's say an object (e.g. variable) who's changes you want to be cascaded throughout your program. KVC allows you to hook up data to objects and may be helpful if you're using Core Data.

I'd start with notifications first.




回答3:


It is very possible and there are 2 ways to do it.

Programatically by making a UILabel in the code and simply setting the myLabel.text.text of it

Though Interface Builder where you drag and drop the UILabel where you want it and have a property in the code to hook it up to and then use that property to set the myLabel.text on it.



来源:https://stackoverflow.com/questions/2092891/how-to-bind-value-of-uilabel-to-an-instance-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!