Monday, February 21, 2011

Accessing properties of programmatically created UIButton from within a method

I have created several UI elements in the viewDidLoad method. I want to change the color of a particular UIButton from within one of my methods. How can I do this? I've tried something similar to: self.view.myUIButton.backgroundColor = myUIColor That doesn't work. What am I missing?

From stackoverflow
  • Useless you set the buttons as properties of the view controller, it loses the locally scoped references to them when the -viewDidLoad method completes.

    You can set the tag attribute for the buttons and then save the tags in a property. Then you can walk the viewController.view.subviews to find the subview with the right tag.

    That latter is very cumbersome and shold be used only if your interface elements are highly variable.

    In most cases you want something like:

    UIButton *button1;
    UIButton *button2;
    @property(nonatomic, retain)  UIButton *button1;
    @property(nonatomic, retain)  UIButton *button2;
    

    then in viewDidLoad you would use:

    self.button1=[[UIButton alloc] initWithFrame:aRect];

    then in any other method you could access the specific button with self.button1.someAttribute

    moshy : RE: tags, you can just use viewWithTag: instead of interating the subviews

0 comments:

Post a Comment