Objective-c – Objective C – Help with changing background color when UIButton is pressed

ipadobjective cuibutton

I am new to programing and any help is appreciated. I am trying to change the background color of a button once it has been pressed. I have tried setBackgroundColor without success. I am not sure that it is compatible with UIButton. Is there any way to programatically accomplish such a task? All thoughts and suggestions are appreciated.

Best Answer

I woudl suggest creating a simple image that contains the background color you want and setting that via the existing methods in the UIButton. (check Wrights Answer for the doc link).

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
NSString* fileLocation = [[NSBundle mainBundle] pathForResource:@"buttonBG" ofType:@"png"];
UIImage* bgImage = [UIImage imageWithContentsOfFile:fileLocation];
if (bgImage != nil) { // check if the image was actually set
  [button setBackgroundImage:bgImage forState:UIControlStateHighlighted];
} else {
  NSLog(@"Error trying to read the background image");
}

That should do the trick. There might be an even better way to create the necessary image on the fly, but that's stuff I'm not firm in.

[edit: a bit more verbose code ]

Related Topic