简体   繁体   中英

How to add custom controls in Interface Builder (Xcode)

So I've created a custom control inherited from UIView and I want to use it in Interface Builder. I know I can add an UIView and set its class name to my custom control class name but it only appears on runtime; in interface builder it's just a regular UIView. I want to see the control while I am working on the UI in interface builder.

Thanks

Xcode 6 has added a form of support for placing and previewing custom controls. See the official Apple docs on "Creating a Custom View That Renders in Interface Builder": https://developer.apple.com/library/ios/recipes/xcode_help-IB_objects_media/chapters/CreatingaLiveViewofaCustomObject.html

Short answer: You can't. (Changed 14 April 2015: See edit at end)

Xcode 3 used to support interface builder plug-ins, but they dropped this in Xcode 4, and from what I've read, will not be adding it back.

You ALSO can't see/see custom outlets/properties of your custom UIView subclasses.

There IS a way to set those properties however. You select the custom view object, select the identity inspector, and look for a section titled "User Defined Runtime Attributes." You can add KVC key path references to properties or sub-properties of your views here, although the number of data types you can specify is limited. Also, if the key path is not a valid KVC reference at runtime, your program will crash with a cryptic, hard-to-find error to the effect that "the object MyCustomView is not key-value compliant for the key foo". If you forget that you set a user defined runtime attribute you can pull your hair out for hours trying to figure out the source of the error.

Edit: (14 April, 2015)

In Xcode 6, Apple added a new IBDesignable attribute that you can add to your custom UIView classes (or NSView classes on Mac OS) that allows you to display the view right in your IB editor. There's also an IBInspectable property that lets you see and edit certain attributes of your views from IB. This is like the "User Defined Runtime Attributes" option we've had since Xcode 4.0, but much cleaner since it shows you the attributes that you can change rather than you're having to type KVC keys, and risk crashing your app if you get something wrong. However, you can only specify a very limited number of types (String/localized string, number, color, boolean, point, size, rect, range, image, or a nil value.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM