Creating a custom view using a xib

nibviewxamarin.iosxib

Using MonoTouch, I'm trying to make a custom view, so I can reuse this view multiple times in a screen. (it's a bunch of labels and buttons)
After reading the answer to this post:
How to add a custom view to a XIB file defined view in monotouch
I must be getting close, but this only seems to allow me to add a custom view, defined in in myCustomView.CS, but what I'm looking for is a way to use a separate .XIB to design my custom view in the interface builder and only use the corresponding cs-file to add logic.
If I try to make a XIB with the same name, the contents won't become visible.

Followed steps:

  • In MyCustomView.CS I have put [Register("MyCustomView")] .

  • I implemented the constructor public MyView(IntPtr handle) : base(handle) {}

  • Open ViewController.XIB in Interface Builder, add a UIView and set it's Class to MyCustomView.

When I run this code, I see the newly added UIView, but not the elements inside of the view, i.e. the contents of MyCustomView.XIB

If I add something to the code of MyCustomView.CS, like this.Backgroundcolor = UIColor.Blue; this is displayed, but any elements added to the .XIB are not. How do I tell Monotouch to display all the stuff defined inside MyCustomView.XIB?

In Objective-C samples I see stuff like "initWithNib"
Unfortunately the "LoadNib" section is not documented in in the Monotouch api, but that sounds like something I should do, but how and where?

Best Answer

Based on my experience in obj-c code, I will try the following code:

var views = NSBundle.MainBundle.LoadNib(nibName, this, null); // (1)
MyCustomView myView = Runtime.GetNSObject(views.ValueAt(0)) as MyCustomView; // (2)

(1) allows you to load the xib file

(2) allows you to convert to convert an IntPtr into an appropriately typed NSObject (sub-)type.

Once you have myView you can add it as a traditional view. Check if you have set up the outelt for your view correctly.

P.S. If you provide some other details we could help you. Furthermore, check the code because I've written by hand.

Related Topic