UIButton:添加渐变层,标题不再显示 - 如何修复? [英] UIButton: Add gradient layer and title is not shown anymore - how to fix?

查看:9
本文介绍了UIButton:添加渐变层,标题不再显示 - 如何修复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的代码向 UIButton 添加渐变层.工作正常,但标题不再可见.有人知道怎么解决吗?

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);

这篇关于UIButton:添加渐变层,标题不再显示 - 如何修复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆