简体   繁体   中英

Change the string of UILabel.text

aClass.aString = @"A";
self.aLabel.text = aClass.aString;

If I change aClass.aString to "B", also want self.aLabel.text change to "B" automatically.

How it works?

Is there a strong link exist that I can built between aClass.aString and self.aLabel.text? I knew that there some way to do this in objective-c, delegate and KVO , but it get a lot stuff to do, it's there some easy way?

You'll have to manage that yourself. If you look at the definition of the UILabel text property ( link ) you'll see that it copies the string contents, precisely for this very reason:

@property(nonatomic, copy) NSString *text

You could write a custom setter method for the aString property:

- (void)setAString:(NSString *)aString
{
    _aString = aString;
    self.aLabel.text = aString;
}

(If you are following the current trend of letting clang generate the backing instance variables and accessor methods for you, then you will probably need to explicitly declare this particular one, ie using an instance variable called _aString ).

One more way other than overriding the setter method,

- (void)setAString:(NSString *)aString

is using KVO to observe change in the string value.

[self addObserver: self
        forKeyPath: @"aString"
           options: NSKeyValueObservingOptionNew
           context: NULL];

Implement this method. It will get called whenever the string value changes.

-(void) observeValueForKeyPath: (NSString *)keyPath ofObject: (id) object
                    change: (NSDictionary *) change context: (void *) context
{
    //Set the label's text with new value.
}

You may want to use the mechanism better explained here:

Is there any data binding mechanism available for iOS?

The gist of it is there's no nice way to do it; there are, however, messy ways to do it using NSNotificationCenter and listening for specific changes.

UI bindings themselves don't exist on iOS (it was my biggest shock when converting from Mac OS X to iOS).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM