Search code examples
objective-ciphonecocoa-touchuibutton

Is it possible to change a UIButtons background color?


This one has me stumped.

Is it possible at all to change the background color of a UIButton in Cocoa for iPhone. I've tried setting the background color but it only changes the corners. setBackgroundColor: seems to be the only method available for such things.

[random setBackgroundColor:[UIColor blueColor]];
[random.titleLabel setBackgroundColor:[UIColor blueColor]];

Solution

  • This can be done programmatically by making a replica:

    loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    loginButton.backgroundColor = [UIColor whiteColor];
    loginButton.layer.borderColor = [UIColor blackColor].CGColor;
    loginButton.layer.borderWidth = 0.5f;
    loginButton.layer.cornerRadius = 10.0f;
    

    edit: of course, you'd have to #import <QuartzCore/QuartzCore.h>

    edit: to all new readers, you should also consider a few options added as "another possibility". for you consideration.

    As this is an old answer, I strongly recommend reading comments for troubleshooting