Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

c# - How to add a custom view to a XIB file defined view in monotouch

I'm trying to learn monotouch at the moment, and following the learn monotouch book by Mike BlueStein. Not a bad book, but it's slightly outdated since xcode 4 (i believe) and a newer version on monotouch has come out.

Anyways, in my project I have a controller and a xib file. I also have a custom view (e.g. myview : UIView), that overrides the draw method. I want to show my custom view next to or on top of the view defined in the xib file. How do I do this?

In the controller, If I override the LoadView method, and set the View to an instance of my custom view, then I can see it, but I loose everything defined in the xib file. If I try to add as a sub view, it does not appear at all.

What am I missing? If the question is not clear, please ask me, so I can clarify.

Cheers.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Follow the following steps to use a custom view in a XIB:

First, decorate the view with the RegisterAttribute:

[Register("MyView")]
public class MyView : UIView
{
}

and implement the following constructor:

public MyView(IntPtr handle) : base(handle) {}

This constructor is needed for when the runtime will try to recreate the view after it has been destroyed by a memory warning. After you have created your custom class:

  • Open the XIB in Xcode (always by double-clicking on it through MonoDevelop) and add a UIView where you want it.
  • In Xcode, set that UIView's class to MyView (or whichever name you passed to the RegisterAttribute):

Custom class for custom view

  • Compile-Run.

EDIT:

Do not override LoadView for controllers that are loaded from a XIB. LoadView is meant to create the controller's view when that controller's view is not loaded from a XIB.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...