子类UIView(另一个子类UIView子)的绘制方法不叫
问题描述:
我有一个子类父UIView
对象,它应该添加另一个子类UIView
。这是UIView
我想补充以及其中Draw
方法不叫:子类UIView(另一个子类UIView子)的绘制方法不叫
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
。父级中的对象绘制得很好,除了圆圈,即使我使用下面的代码作为圈子它显示正确。所以约束是好的。
UIView circle = new UIView() { BackgroundColor = UIColor.Red };
我在做什么错了?我不能重写Draw
方法(在子类父类和子类圈)? PS:我必须指出,圆圈应该重叠一条线。但Draw
永远不会被调用,所以它似乎没有得到一个框架。
答
你是否知道你正在实例化一个UIView而不是这段代码中的Circle被剪切掉?
UIView circle = new UIView() { BackgroundColor = UIColor.Red };
而且你不应该在抽签方法中添加子视图,因为它会被称为多的时间,其实你应该只覆盖绘制方法和你正在做一个自定义绘制(it's的圆视图的情况,但不是父视图的情况)。
从苹果单证:
查看图纸出现需要的基础上。当第一次显示视图时, 或由于版面更改而全部或部分视图变为可见时,系统会要求视图绘制其内容。对于包含 自定义内容使用的UIKit或核心图形视图,系统调用 视图的drawRect:方法
所以,你可以张贴代码鹬,你实际添加父视图?和父视图的代码,你可能会覆盖一个方法,并没有调用基类方法(如setNeedsDisplay或类似的东西),或者你不添加视图。
我把父母代码从'Draw'移到构造函数中,现在显示了圆圈!谢谢! – testing