我一直試圖通過從UIView類擴展來創建自定義視圖。我找到的所有示例都覆蓋了Draw方法,但是我不需要繪製任何東西,只需要在其他視圖/控件中填充視圖,在控制器中的ViewDidLoad中完成時,此工作正常,但只要我嘗試使它成爲一個自定義類,事情出錯... 據我所知,創建「複合」視圖時必須重寫LayoutSubViews方法Monotouch:如何使可複用的複合視圖
視圖具有子視圖是無關緊要的,這是隻是一個例子:
[寄存器( 「PhotoLabel」)]
公共類PhotoLabel:UIView的 {
public PhotoLabel() : base() {} public PhotoLabel (IntPtr p) : base (p) {} public PhotoLabel (RectangleF rect) : base (rect) {} public override void LayoutSubviews() { base.LayoutSubviews(); if (Image != null) { AddSubviews (ImageView, Label); } else { AddSubview (Label); } } public UIImage Image { get { return ImageView.Image; } set { ImageView.Image = value; SetNeedsDisplay(); } } UIImageView ImageView { get { var iFrame = new RectangleF (0, 0, this.Frame.Height, this.Frame.Height); return new UIImageView() { Frame = iFrame, ContentMode = UIViewContentMode.Center, Image = this.Image.Scale (new SizeF (iFrame.Width, iFrame.Height)) }; } } public string Text { get { return Label.Text; } set { Label.Text = value; SetNeedsDisplay(); } } UILabel Label { get { var x = Image != null ? this.Frame.Height : 0; var width = Image != null ? this.Frame.Width - this.Frame.Height : this.Frame.Width; var lFrame = new RectangleF (x, 0, width, this.Frame.Height); return new UILabel() { Frame = lFrame, ContentMode = UIViewContentMode.Center, TextAlignment = UITextAlignment.Left, Text = this.Text, Font = UIFont.BoldSystemFontOfSize (17), BackgroundColor = UIColor.Clear }; } } }
,我試圖用它作爲這樣的:
public override void ViewDidLoad() { base.ViewDidLoad(); var pLabel = new PhotoLabel() { Frame = new RectangleF (5,5, 100, 60), Image = UIImage.FromFile ("photo.png"), Text = "some text" }; this.View.AddSubview (hCell); }
我俯瞰東西猜,我非常清楚地知道該怎麼做,在安卓(MonoDroid的)但因爲我對iOS和MonoTouch很新,所以我不知道我在這裏做錯了什麼。所以如果任何人都可以指導我或者給我提供一個這樣的例子或者類似的例子,我們將不勝感激。