I've been trying to create a custom view, by extending from the UIView class. All the examples i find override the Draw method, but i don't need to draw anything I just need to fill the view with other views/controls, when done in the ViewDidLoad in a controller, this works fine, but as soon as I try to make it a Custom class, things go wrong... As far as i could find, when creating "compound"views one has to override the LayoutSubViews method
what the view has as subviews is irrelevant, this is just an example :
[Register ("PhotoLabel")]
public class 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 }; } } }
And i tried to use it as such:
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); }
Guess I'm overlooking something, I know very well how to do that in Android (monodroid), but as I'm pretty new to iOS and MonoTouch, i have no idea what I'm doing wrong here. So if anyone can direct me to or provide me with a working example of this or smth similar, it would be appreciated.