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);
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);
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With