This was my answer in response to:
in http://stackoverflow.com/questions/14738964/how-do-you-add-a-custom-uiviewcontroller-to-existing-xib/
----
For a normal UIView, the basic steps you need to go through are:
For a custom UICollectionView, UILabel, UITableViewCell, or any other UIView base class, then you follow similar steps, just with a different base class and with different constructors too in order to support the specific View.
For a video about custom Table cells, see: http://slodge.blogspot.co.uk/2013/01/uitableviewcell-using-xib-editor.html
I cannot figure out how to add a custom control to the XIB.
in http://stackoverflow.com/questions/14738964/how-do-you-add-a-custom-uiviewcontroller-to-existing-xib/
----
For a normal UIView, the basic steps you need to go through are:
- Create your custom view in C# as a class
public class MyView { }
- Add the UIView base class to it, add a Register attribute and add two constructors:
[Register("MyView")] public class MyView : UIView { public MyView() {} public MyView(IntPtr handle) : base(handle) {} }
- To make it do something useful, then add a Draw implementation:
public override Draw(RectangleF rect) { var context = UIGraphics.CurrentGraphics(); UIColor.Red.SetFill(); context.FillEclipseInRect(rect); }
- Save and Build your project
- Now double click on the XIB for the UIViewController in which you want to use your custom view.
- This will open up the XIB editor in xCode
- In the editor, add a UIView to the design surface
- Select that UIView and in the Identity Inspector, set the UIView's "Custom Class" to "MyView"
- Save everything in XCode
- Return to MonoDevelop, build and run
For a custom UICollectionView, UILabel, UITableViewCell, or any other UIView base class, then you follow similar steps, just with a different base class and with different constructors too in order to support the specific View.
For a video about custom Table cells, see: http://slodge.blogspot.co.uk/2013/01/uitableviewcell-using-xib-editor.html
Hi Stuart, great tip!
ReplyDeleteBut what do I do if I create the custom view in Interface Builder (and not in code)? So I create a custom view in IB, and then specify it to be of type CustomView. I then add various UI controls to it.
In CustomViewController's view, I add a UIView and change its type to my CustomView. But when I compile and run, that view is blank!
Can you post a repo? Will get it working ;)
DeleteHi Stuart
ReplyDeleteThanks for the quick response! Apologies for my delayed one; basic repo at https://github.com/mrtnkrstn/MyCustomView
Thank you so much for helping with this! Noticed that you are at Xamarin Evolve, wish I was able to attend. Following the proceedings in spirit; enjoy!
Hi Stuart
ReplyDeleteThanks for your help :) I somehow never stumbled upon Nib.Instantiate(). Would have been so nice if all of this could have been done straight in Interface Builder though.
Again, thanks for the help!
Can we add UIButtons in these Custom Views ?
ReplyDelete