我正在尝试创建一个从 UIButtonType.RoundedRect
扩展而来的自定义 UIButton。
我添加的功能可以正常工作,但我的按钮的初始圆角边框状态存在问题。我的扩展按钮的边框在被点击后才会绘制。
更新(2013 年 1 月 24 日):根据 Richard Marskell 的要求添加了红色背景测试的结果,该结果仅绘制了按钮的标签。 BackgroundColor = UIColor.Red;
下面是我创建自定义按钮的源代码。
public class TestView : UIView
{
public TestView(IntPtr p) : base(p) { }
public TestView(RectangleF bounds)
{
Frame = bounds;
BackgroundColor = UIColor.White;
UIButton button1 = new UIButton(UIButtonType.RoundedRect);
button1.Frame = new RectangleF(20,20,100,50);
button1.SetTitle("Button 1", UIControlState.Normal);
AddSubview(button1); // Drawn Correctly
MyButton button2 = new MyButton();
button2.Frame = new RectangleF(20,90,100,50);
button2.SetTitle("Button 2", UIControlState.Normal);
AddSubview(button2); // Only drawn correctly after Tap
// EDIT: Added to test Miguel's theory
UIButton button3 = UIButton.FromType(UIButtonType.RoundedRect);
button3.Frame = new RectangleF(20,160,100,50);
button3.SetTitle("Button 3", UIControlState.Normal);
AddSubview(button3); // Drawn Correctly
}
}
public class MyButton : UIButton
{
public MyButton() : base(UIButtonType.RoundedRect) { }
}
- 我只是不确定如何在加载 View 时强制正确绘制边框。
- 我不需要
UIButtonType.Custom
类型的按钮,因为我不想自己设置按钮的样式。 - 当我调试时,我将 MyButton 的类型正确设置为
UIButtonType.RoundedRect
。 - MyButton (button2) 的 UIButton 基本属性与 UIButton 实例 (button1) 的属性匹配。
我该如何解决这个问题?
更新(2013 年 1 月 31 日):Herman Schoenfeld 为这个错误提供了一个合适的解决方案。
最佳答案
这行得通
public class MyButton : UIButton
{
public MyButton() : base(UIButtonType.RoundedRect) { }
public override RectangleF Frame {
get {
return base.Frame;
}
set {
var temp = TranslatesAutoresizingMaskIntoConstraints;
TranslatesAutoresizingMaskIntoConstraints = false;
var constraints = new [] {
NSLayoutConstraint.Create(this, NSLayoutAttribute.Width, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1.0f, value.Width),
NSLayoutConstraint.Create(this, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1.0f, value.Height)
};
AddConstraints(constraints);
SizeToFit();
RemoveConstraints(constraints);
base.Frame = value;
TranslatesAutoresizingMaskIntoConstraints = temp;
}
}
}
这只是一个解决方法,它似乎是一个错误。 SizeToFit() 解决了这个问题,其他代码维护了框架。
关于c# - 最初未绘制扩展的 UIButton 边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14081410/