Clear IBDesignable views have black background
Asked Answered
L

1

8

I'm attempting to create an IBDesignable class which can have a transparent background when rendered in Interface Builder. So far, I've gotten opaque black backgrounds. I've set up a simple demonstration of the issue:

I've placed a UIView in this scene in Interface Builder. You can't see it because its background is clear. This is what should the scene should look like.

A screenshot of an empty scene in interface builder

The only difference in this screenshot is that I've set the class of our previously invisible view to be 'DesignableView'.

A screen shot of an Interface Builder scene with a black box in the middle

Here is the entire implementation of the DesignableView class:

#import <UIKit/UIKit.h>

IB_DESIGNABLE
@interface DesignableView : UIView
@end

@implementation DesignableView
- (void)drawRect:(CGRect)rect {
    //rendering code goes here
}
@end

Is there a way to give the IBDesignable view the correct, transparent background?

Lax answered 2/1, 2015 at 17:20 Comment(2)
If you're not using drawRect: you should comment it out; it effects performance. That might also be the issueSinuosity
It's true having an empty implementation of drawRect: is a bad idea, however that point is not relevant for this question. In this example, the drawRect: function is empty because it's the simplest way to reproduce the issue of having a black background in IB.Lax
S
11

I just remembered how I fix this. You need to override layoutSubviews

- (void)layoutSubviews
{
    [super layoutSubviews];

    self.backgroundColor = [UIColor clearColor];
}
Sinuosity answered 2/1, 2015 at 20:43 Comment(1)
Thanks, Chris! This works great. I've found that this trick also works when the call to set self.backgroundColor is made in the prepareForInterfaceBuilder function, which might be a preferable place.Lax

© 2022 - 2024 — McMap. All rights reserved.