如何在单点触控中将自定义视图添加到 XIB 文件定义的视图 [英] How to add a custom view to a XIB file defined view in monotouch
问题描述
我目前正在尝试学习单点触控,并遵循 Mike BlueStein 的学习单点触控书.不错的书,但自从 xcode 4(我相信)和关于单点触控的更新版本问世以来,它有点过时了.
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.
无论如何,在我的项目中,我有一个控制器和一个 xib 文件.我还有一个自定义视图(例如 myview : UIView),它覆盖了 draw 方法.我想在 xib 文件中定义的视图旁边或顶部显示我的自定义视图.我该怎么做?
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?
在控制器中,如果我覆盖 LoadView 方法,并将 View 设置为我的自定义视图的一个实例,那么我可以看到它,但是我丢失了在 xib 文件中定义的所有内容.如果我尝试添加为子视图,它根本不会出现.
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.
干杯.
推荐答案
按照以下步骤在 XIB 中使用自定义视图:
Follow the following steps to use a custom view in a XIB:
首先,使用 RegisterAttribute
装饰视图:
First, decorate the view with the RegisterAttribute
:
[Register("MyView")]
public class MyView : UIView
{
}
并实现以下构造函数:
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:
- 在 Xcode 中打开 XIB(总是通过 MonoDevelop 双击它)并在需要的位置添加
UIView
. - 在 Xcode 中,将该 UIView 的类设置为 MyView(或您传递给
RegisterAttribute
的任何名称):
- 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
):
- 编译运行.
不要覆盖从 XIB 加载的控制器的 LoadView
.LoadView
用于在控制器的视图不是从 XIB 加载时创建控制器的视图.
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.
这篇关于如何在单点触控中将自定义视图添加到 XIB 文件定义的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!