Duck
Duck

Reputation: 35953

Intercepting a setter for a known property of UIButton and setting its value

Suppose I was creating a property for a class, like

@property (nonatomic, strong) NSString *name;

If I was to create a setter for this I would use

- (void)setName:(NSString *)name {
  _name = name;
  // ... bla bla...
}

Notice the first line? I am assigning the new name to the internal variable of that property.

Now suppose I want to change the background color of a UIButton programmatically if the button is on the selected state.

So, I thought I could intercept the setter of the selected property, like this:

- (void)setSelected:(BOOL)selected {
  self.backgroundColor = selected ? [UIColor redColor] : [UIColor darkGrayColor];
}

But there is no apparent way to set the "internal" value of that property. It will not accept _selected = selected and if I use self.selected = selected I will create a crash condition of the setting calling the setter infinite times.

How do I do that?

Upvotes: 0

Views: 71

Answers (1)

Willeke
Willeke

Reputation: 15589

To set an inherited property, call super:

[super setSelected:selected];

or

super.selected = selected;

Upvotes: 1

Related Questions