iOS >> Why isn't it Possible to Set UIControls Properties Directly in Code When Approaching Them via "sender"?

StackOverflow https://stackoverflow.com/questions/18121507

Question

Let's say that I wish to approach a certain UIControl in a certain method that it triggers - I can send the method a pointer to the UIControl using "sender". but then, for some reason, I cannot approach sender's properties directly and have to use the setX:forState: methods. If I approach the properties directly, I get no error or warning; it simply does nothing...

Here's an example:

h. file...
@interface MYViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *dButton; //connected to a UIButton in IB
-(IBAction)dButtonClick:(UIButton*)sender; //connected to the same UIButton in IB
@end

then...

m. file...
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.dButton.titleLabel.textColor = [UIColor greenColor]; //this is working...
}
-(IBAction)dButtonClick:(UIButton*)sender 
{
    sender.titleLabel.textColor = [UIColor redColor]; //this is not working...
    self.dButton.titleLabel.textColor = [UIColor redColor]; //this is also not working...
    [sender setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; //only this is working. 
    //But why?!?!?
}

I tried to search for some info about the way these items work, but couldn't find anything that explains the logic behind it clear enough.

Any help would be... well... helpful...

Was it helpful?

Solution

This:

sender.titleLabel.textColor

And this:

[sender setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

Are different not just because of the dot notation but also because of the state. The button has different colours for each state so any colour set directly will be overridden by the colour for the state.

This line:

self.dButton.titleLabel.textColor = [UIColor redColor];

Could be the same issue or you may just not have connected the outlet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top