最初不绘制扩展的UIButton边框

Sco*_*ott 31 c# mono uibutton uikit xamarin.ios

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

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

之前的截图

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

调试

我该如何解决这个问题?


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

Her*_*eld 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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这只是一种解决方法,它似乎是一个错误.SizeToFit()修复了问题,其他代码维护了框架.