Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IBDesignable UIViewController

I'd like to be able to layout my view controller in code but see the layout displayed in interface builder.

I know I can create a UIView subclass, make that IBDesignable, and assign it to the view controller's view, but this would require that I make all other subviews properties of this UIView subclass instead of properties of the view controller.

The real desire is to be able to layout my view controllers in code but quickly see any changes without rebuilding the project. If this is possible with playgrounds instead, an answer describing how to do that would also be appreciated.

Thanks for any suggestions.

like image 580
Jeff Ames Avatar asked Nov 06 '14 23:11

Jeff Ames


People also ask

What is IBDesignable and IBInspectable?

IBDesignable is user defined run time. Mean that if any IBDesignable view is rendered on the storyboard, you will find the view and change the value of the IBInspectable property, this will directly reflect on the storyboard without running the app. IBInspectable is run time property, this works as key coding value.

What is the use of @IBDesignable?

@IBInspectable allows us to create attributes in code that we can assign in a storyboard or a . xib file. For example, when we want a cornerRadius property available in a Storyboard, we create a cornerRadius property inside our custom view and mark it with @IBInspectable .

What is IBInspectable?

The @IBInspectable keyword lets you specify that some parts of a custom UIView subclass should be configurable inside Interface Builder. Only some kinds of values are supported (booleans, numbers, strings, points, rects, colors and images) but that ought to be enough for most purposes.


1 Answers

I found a workaround to test view controller layout using IBDesignable.

1.Layout your view controller in code just as you'd do normally

2.Create an IBDesignable UIView subclass and add the view controller's view as a subview.

3.Create a xib and set the class of its view to the subclass you created in step 2

To elaborate on step 2, your IBDesignable's initWithFrame: method may look like

{
    self = [super initWithFrame:frame];
    MyViewController *viewController = [MyViewController alloc] init];
    viewController.view.frame = self.bounds;
    [self addSubview:viewController.view];
    return self;
}

So beyond this initWithFrame method, all of your layout code can be handled by your view controller. You may want to pass data to your view controller in your subview's prepareForInterfaceBuilder method.

like image 186
Jeff Ames Avatar answered Oct 11 '22 07:10

Jeff Ames