最初不绘制扩展的UIButton边框

时间:2012-12-29 11:56:48

标签: c# mono xamarin.ios uibutton uikit

我正在尝试创建一个从UIButtonType.RoundedRect扩展的自定义UIButton。

我添加的功能正在运行,但我的按钮的初始圆角边框状态存在问题。我的扩展按钮的边框在点击之后才会被绘制。

Before-After Screenshot

更新(2013年1月24日):根据Richard Marskell的要求添加了红色背景测试的结果,该结果仅得出按钮的标签。 BackgroundColor = UIColor.Red;

Red Background Test, Before-After Screenshot

以下是我创建自定义按钮的源代码。

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) { }
}
  • 我只是不确定在加载视图时如何强制正确绘制边框。
  • 我不需要UIButtonType.Custom类型的按钮,因为我不想自己设置按钮的样式。
  • 当我调试I时,MyButton的类型被正确设置为UIButtonType.RoundedRect
  • MyButton(button2)的UIButton基本属性与UIButton实例(button1)的属性匹配。

Debug

如何解决此问题?


更新(2013年1月31日):Herman Schoenfeld为此错误提供了合适的解决方案。

1 个答案:

答案 0 :(得分:7)

这有效

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()修复了问题,另一个代码维护了框架。

相关问题