如何创建自定义 UIView?
我创建了一个 UIView 子类和相应的 xib 文件,其中放置了一些 UILabels 和 UIImageViews。然后我想将此自定义 UIView 的多个副本放入 UIViewController 中。
当我这样做时,它们在界面生成器中显示为空白,并且在应用程序加载时不会出现。我需要在 UIView 子类上实现哪些方法才能实现此功能?
I've created a UIView subclass and corresponding xib file where I've laid out some UILabels and UIImageViews. I want to then put multiple copies of this custom UIView into a UIViewController.
When I do that they appear blank in interface builder and don't appear when the app loads. What methods do I need to implement on the UIView subclass to make this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
到目前为止,最简单的方法是创建一个笔尖,将文件所有者设置为 NSObject,其中包含一个包含布局元素的视图。
然后
无需对文件所有者执行任何操作;这里甚至被设置为零。
The easiest method by far is to create a nib with File's Owner set to NSObject, containing one view containing your layout element.
Then
No need to do anything with the file's owner; it is even set to nil here.
这类似于使用 nib 文件创建表视图单元格。 这里 是讨论如何做到这一点的页面。
您需要在自定义视图的
UIViewController
子类中放置一个插座,并将UIViewController
子类设置为自定义视图笔尖 (.xib) 中的“文件所有者” ) 文件。然后将您创建的插座连接到顶级视图对象(同样在您的自定义视图 nib 文件中)。然后,每次您想要在视图控制器代码中实例化自定义视图时,请调用:
您添加的插座将被设置为指向自定义视图的新实例。
这种方法的唯一缺点是您必须以编程方式而不是在界面生成器中以图形方式在视图控制器中布置自定义视图的实例。
另一种方法是以编程方式在
UIView
子类中创建放置标签和图像,然后您可以将其添加到界面构建器,就像添加任何其他UIView
子类一样。This is similar to using a nib file to create table view cells. Here is a page that discusses how to do that.
You'll need to put an outlet in your
UIViewController
subclass for the custom view, and set theUIViewController
subclass as the "File's Owner" in your custom view nib (.xib) file. Then connect the outlet you created to the top-level view object (again in your custom view nib file).Then each time you want to instantiate your custom view in your view controller code, call:
The outlet you added will then be set to point to a new instance of your custom view.
The only downside to this approach is that you will have to lay out the instances of your custom view in your view controller programatically rather than graphically in interface builder.
Another approach would create the put labels and images programatically in your
UIView
subclass, and then you can add it to interface builder like you would any otherUIView
subclass.编辑:不幸的是,在 Xcode 4.0 中,此功能已被删除。
在 Interface Builder 中配置子视图后,您可以创建一个新组(使用库窗口底部的齿轮按钮)并从列表视图(即不是布局)中拖动子类对象(包含图像和标签)查看)返回到库窗口。
然后,您可以以图形方式将视图子类的多个实例添加到任何界面构建器视图或窗口,就像使用库中的内置对象一样。
Edit: Unfortunately in Xcode 4.0, this capability was removed.
Once you have your subview configured in Interface Builder, you can create a new group (use the cog button at the bottom of the library window) and drag your subclass object (containing your images and labels) from the list view (i.e. not the layout view) back to the library window.
You can then graphically add multiple instances of your view subclass to any interface builder view or window like you would with the built-in objects in the library.