0

I want to create a string to use in place of the name of a button.

For example, I want to set the background of a button programmatically. But I want the name to come from a string variable. That way, if I want to change the background image of a button called Button1, I could put "Button1" into my NSString and call it myButton...and then reference the actual Button1 as "myButton"

How would I do this?

user1824518
  • 213
  • 1
  • 4
  • 12
  • Can you show some of the code you've tried so far? Maybe we can find a simple syntax/logic error that's preventing it from working. – Austin Mullins Mar 14 '13 at 02:47
  • Can you clarify what's going on here? There's a method called `setBackgroundImage:forState:` that you can use. [This post has more details.](http://stackoverflow.com/questions/4608454/setting-a-background-image-for-uibutton) – aqua Mar 14 '13 at 02:52

1 Answers1

1

It's not very clear to me what you exactly want to do, but I'll try to guess.

Suppose you have a IBOutlet referencing the UIButton like this

@interface MyViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton * myButton;
@end

You can use KVC to change the value of that button given the property name

@implementation MyViewController

- (void)changeBackgroundOfButtonNamed:(NSString *)buttonName {
    UIButton * button = [self valueForKey:buttonName];
    // Change the background
    // ...
}

- (void)whatever {
    [self changeBackgroundOfButtonNamed:@"myButton"];
}
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235