xcode 你如何在 InterfaceBuilder 中显示自定义 UIViews?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/494520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you display custom UIViews in InterfaceBuilder?
提问by Frank Krueger
I seem to enjoy designing new UIViews
and UIControls
that implement their own -drawRect:
method. This work well for me, especially when composed using UIViews
in Interface Builder.
我似乎喜欢设计新的UIViews
并UIControls
实现自己的-drawRect:
方法。这对我来说效果很好,尤其是UIViews
在Interface Builder 中组合使用时。
But composing them in Interface Builder is annoying because they just show up as boring plain rectangles.
但是在 Interface Builder 中组合它们很烦人,因为它们只是显示为无聊的普通矩形。
It would be great if the views would actually render themselves as the built-in controls do.
如果视图真的像内置控件那样呈现自己,那就太好了。
Is there any way I can structure my project so that Interface Builder will render my custom views?
有什么方法可以构建我的项目,以便 Interface Builder 呈现我的自定义视图?
采纳答案by Jason Coco
In order to do this, you actually have to create a plug-in for Interface Builder that uses your custom class. Once you create and install your plug-in, you will be able to drag and drop instances of your class (your view) onto another window/view/whatever just like any other control. To get started with creating IB Plug-Ins, please see the Interface Builder Plug-In Programming Guide. Also, I recommend taking a look at Aaron Hillegass's book, Cocoa Programming for Mac OS X. As well as being very well written and easy to understand, it has a chapter on creating your own IB Palette controls.
为了做到这一点,您实际上必须为使用您的自定义类的 Interface Builder 创建一个插件。创建并安装插件后,您将能够将类的实例(您的视图)拖放到另一个窗口/视图/任何其他控件上。要开始创建 IB 插件,请参阅Interface Builder Plug-In Programming Guide。另外,我建议您阅读 Aaron Hillegass 的书Cocoa Programming for Mac OS X。除了写得很好且易于理解外,它还有一章关于创建您自己的 IB Palette 控件。
回答by tebs1200
This is achievable by marking your UIView subclass with @IBDesignable
. Once you do this, your custom views will render themselves in Interface Builder. You can even add parameters that can be configured by marking them as @IBInspectable
. Here's a Swift example:
这可以通过用 标记你的 UIView 子类来实现@IBDesignable
。完成此操作后,您的自定义视图将在 Interface Builder 中呈现。您甚至可以添加可以通过标记为@IBInspectable
. 这是一个 Swift 示例:
@IBDesignable class customView: UIView {
@IBInspectable var count: Int = 0
}
There's an article on NSHipsterthat provides more detail.
有一篇关于 NSHipster的文章提供了更多细节。