2015-05-19 73 views
0

我有一個子類父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永遠不會被調用,所以它似乎沒有得到一個框架。

回答

3

你是否知道你正在實例化一個UIView而不是這段代碼中的Circle被剪切掉?

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

而且你不應該在抽籤方法中添加子視圖,因爲它會被稱爲多的時間,其實你應該只覆蓋繪製方法和你正在做一個自定義繪製(it's的圓視圖的情況,但不是父視圖的情況)。

從蘋果單證:

查看圖紙出現需要的基礎上。當第一次顯示視圖時, 或由於版面更改而全部或部分視圖變爲可見時,系統會要求視圖繪製其內容。對於包含 自定義內容使用的UIKit或核心圖形視圖,系統調用 視圖的drawRect:方法

所以,你可以張貼代碼鷸,你實際添加父視圖?和父視圖的代碼,你可能會覆蓋一個方法,並沒有調用基類方法(如setNeedsDisplay或類似的東西),或者你不添加視圖。

+1

我把父母代碼從'Draw'移到構造函數中,現在顯示了圓圈!謝謝! – testing