Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton: Add gradient layer and title is not shown anymore - how to fix?

I'm using the code below to add a gradient layer to a UIButton. Works fine but the title is not visible anymore. Does anybody know how to fix?

UIButton oAddressBtn = UIButton.FromType (UIButtonType.Custom);
oAddressBtn.Frame = new RectangleF (0, 0, 150, 25);
oAddressBtn.VerticalAlignment = UIControlContentVerticalAlignment.Center;
oAddressBtn.Font = UIFont.FromName("Helvetica", 12);
oAddressBtn.SetTitleColor (UIColor.White, UIControlState.Normal);

// Create a gradient for the background.
CAGradientLayer oGradient = new CAGradientLayer ();
oGradient.Frame = oAddressBtn.Bounds;
oGradient.Colors = new CGColor[] { UIColor.FromRGB (170, 190, 235).CGColor, UIColor.FromRGB (120, 130, 215).CGColor };

// Assign gradient to the button.
oAddressBtn.Layer.MasksToBounds = true;
oAddressBtn.Layer.AddSublayer (oGradient);
oAddressBtn.Layer.CornerRadius = 10;
oAddressBtn.Layer.BorderColor = UIColor.FromRGB (120, 130, 215).CGColor;

// Set the button's title.
oAddressBtn.SetTitle (sAddress, UIControlState.Normal);
like image 923
Krumelur Avatar asked Jan 24 '11 09:01

Krumelur


2 Answers

Ha! Asking a question and then finding it out all by myself...coincidence. I had to change the order. After assigning the gradient, the button's text properties have to be set and not before. Fixed code here:

UIButton oAddressBtn = UIButton.FromType (UIButtonType.Custom);
oAddressBtn.Frame = new RectangleF (0, 0, 150, 25);

// Create a gradient for the background.
CAGradientLayer oGradient = new CAGradientLayer ();
oGradient.Frame = oAddressBtn.Bounds;
oGradient.Colors = new CGColor[] { UIColor.FromRGB (170, 190, 235).CGColor, UIColor.FromRGB (120, 130, 215).CGColor };

// Assign gradient to the button.
oAddressBtn.Layer.MasksToBounds = true;
oAddressBtn.Layer.AddSublayer (oGradient);
oAddressBtn.Layer.CornerRadius = 10;
oAddressBtn.Layer.BorderColor = UIColor.FromRGB (120, 130, 215).CGColor;

// Set the button's title. Alignment and font have to be set here to make it work.
oAddressBtn.VerticalAlignment = UIControlContentVerticalAlignment.Center;
oAddressBtn.Font = UIFont.FromName("Helvetica", 12);
oAddressBtn.SetTitleColor (UIColor.White, UIControlState.Normal);

oAddressBtn.SetTitle (sAddress, UIControlState.Normal);
like image 161
Krumelur Avatar answered Nov 30 '22 07:11

Krumelur


I have no idea how this is done in monotouch. But the answer below is the Obj-C variant for an approach where you don't have to add a sublayer.

Instead of inserting a gradient layer, you can also override the method +layerClass to return the CAGradientLayer class. The layer of the button is than of that class, and you can easily set its colors etc.

+ (Class)layerClass {
    return [CAGradientLayer class];
}
like image 23
Johan Kool Avatar answered Nov 30 '22 07:11

Johan Kool