I have seen in the in-built apps for iphone that there is a red delete UIButton. My question is, how do I change the color of the button. Usually there is a 'tint' attribute in the attributes inspector but there is not when using a UIbutton. Is there any way to programmatically change the color? I appreciate any help.
Asked
Active
Viewed 4,021 times
3 Answers
3
If your button is of type UIButtonTypeRoundedRect
instead of UIButtonTypeCustom
, setting the background color on the layer doesn't work.
Try this, it works for me.
UIButton *myButton = [UIButton buttonWithType: UIButtonTypeRoundedRect];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.buttonAddToOrder.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor redColor] CGColor], (id)[[UIColor redColor] CGColor], nil];
gradient.cornerRadius = 10;
[myButton.layer insertSublayer:gradient atIndex:0];
Hope this may help.

Nej Kutcharian
- 4,054
- 5
- 21
- 27

roberto.buratti
- 2,487
- 1
- 16
- 10
3
That tint color for an UIButton
is only available for the UIGlassButton
which is an private undocumented API. Some solutions around using the private undocumented API are to use images or try drawing your own gradient.
Resources:
http://cocoawithlove.com/2008/09/drawing-gloss-gradients-in-coregraphics.html
3
You can make buttons with colors by using the layer of the button. First add the QuartzCore framework to your project. Then add #import <QuartzCore/QuartzCore.h>
into your view class. To make a red button do this
UIButton *myButton = [UIButton buttonWithType: UIButtonTypeCustom];
[myButton setFrame: CGRectMake(10.0f, 10.0f, 300.0f, 44.0f)];
[[myButton layer] setBackgroundColor: [[UIColor redColor] CGColor]];
[self addSubview: myButton];
[myButton release];
Hope this helps!
-
Put it into the init method of the view in which the button should appear. – dasdom Apr 24 '11 at 21:41
-
I did not down vote this. This is a good implementation, although i prefer drawing an image myself as I get more user friendliness... (like rounded edges) :) I have a question though. What is the difference of putting code like this in the init method of a View Controller rather in the viewDidLoad method? is there a difference? – SEG Nov 12 '11 at 16:17
-
1Today I would prefer to put it into viewDidLoad. Therefore it does not occupy memory until it is needed. – dasdom Nov 12 '11 at 23:50
-
cornerRadius = 8, [button addTarget:self action:@selector(touch:) forControlEvents:UIControlEventTouchDown]; is a nice addition. the touch event can change the layers backgroundColor for a nice affect... – SEG May 04 '12 at 14:56