未调用子类 UIView 的绘制方法(另一个子类 UIView 的子类)

Draw method of subclassed UIView (child of another subclassed UIView) not called

我有一个子类父 UIView 对象,它应该添加另一个子类 UIView。这是我要添加的 UIView 并且未调用 Draw 方法的地方:

public class Circle : UIView
{
    private UIColor color;

    public Circle ()
    {
        this.color = UIColor.Black;

        this.BackgroundColor = UIColor.Clear;
    }

    public Circle (UIColor color)
    {
        this.color = color;

        this.BackgroundColor = UIColor.Clear;
    }

    public override void Draw (CGRect rect)
    {
        base.Draw (rect);

        // Get the context
        CGContext context = UIGraphics.GetCurrentContext ();

        context.AddEllipseInRect (rect);
        context.SetFillColor (color.CGColor);
        context.FillPath ();
    }
}

这就是我添加的方式:

Circle circle = new Circle (UIColor.Red);
circle.TranslatesAutoresizingMaskIntoConstraints = false;
AddSubview (circle);

AddConstraint(NSLayoutConstraint.Create(circle, NSLayoutAttribute.Left, NSLayoutRelation.Equal, line, NSLayoutAttribute.Left, 1, 10));
AddConstraint(NSLayoutConstraint.Create(circle, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, line, NSLayoutAttribute.CenterY, 1, 0));
AddConstraint(NSLayoutConstraint.Create(circle, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1, 6));
AddConstraint(NSLayoutConstraint.Create(circle, NSLayoutAttribute.Width, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1, 6));

上面的代码再次出现在父级的 Draw 方法中。除了圆形外,父对象中的对象绘制得很好,即使我将下面的代码用作 circle 它也能正确显示。所以约束没问题。

UIView circle = new UIView() { BackgroundColor = UIColor.Red };

我做错了什么?我不能覆盖两个 Draw 方法(在子类父类和子类 circle 中)吗?

PS: 不得不提的是圆应该和直线重叠。但是 Draw 从来没有被调用过,所以它似乎没有得到一个框架。

你知道你正在实例化一个 UIView 而不是这个代码片段中的 Circle 吗?

UIView circle = new UIView() { BackgroundColor = UIColor.Red };

另外你不应该在 draw 方法中添加子视图,因为它会被多次调用,事实上你应该只在你进行自定义绘制时覆盖 Draw 方法(这是 Circle 的情况视图,但不是父视图的情况)。

来自苹果文档:

View drawing occurs on an as-needed basis. When a view is first shown, or when all or part of it becomes visible due to layout changes, the system asks the view to draw its contents. For views that contain custom content using UIKit or Core Graphics, the system calls the view’s drawRect: method

那么您可以 post 截取您实际添加父视图的代码吗?以及父视图的代码,您可能已经覆盖了一个方法并且没有调用基本 class 方法(如 setNeedsDisplay 或类似的方法)或者您没有添加视图。