IB_DESIGNABLE,在预览中显示视图?

我在界面构建器中显示了我的IB_DESIGNABLE属性集的视图,但是当我使用预览function查看我的视图在各种设备上的外观时,我只获得了超级视图名称,例如UIView

不要在预览中显示IB_DESIGNABLE视图吗?

编辑按要求的代码+屏幕截图:

 H = #import  IB_DESIGNABLE @interface TitleBannerView : UILabel @property (nonatomic) IBInspectable CGFloat borderWidth; @property (nonatomic) IBInspectable CGFloat cornerRadius; @property (nonatomic) IBInspectable CGFloat shadowHeight; @end M = @implementation TitleBannerView @synthesize borderWidth; @synthesize cornerRadius; @synthesize shadowHeight; - (void)drawRect:(CGRect)rect { if (self.borderWidth == 0) self.borderWidth = 8.5; if (self.cornerRadius == 0) self.cornerRadius = 33; if (self.shadowHeight == 0) self.shadowHeight = 15.1; CGContextRef context = UIGraphicsGetCurrentContext(); //// Color Declarations UIColor* bG = [UIColor colorWithRed: 0.18 green: 0.8 blue: 0.443 alpha: 1]; UIColor* borderColor = [UIColor colorWithRed: 0.557 green: 0.267 blue: 0.678 alpha: 1]; UIColor* shadowColor2 = [UIColor colorWithRed: 0.976 green: 0.859 blue: 0.718 alpha: 1]; //// Shadow Declarations UIColor* shadow = shadowColor2; CGSize shadowOffset = CGSizeMake(-4.1, self.shadowHeight); CGFloat shadowBlurRadius = 1.5; 

//

  //// Frames CGRect frame = self.bounds; //// Subframes CGRect group = CGRectMake(CGRectGetMinX(frame) + 15, CGRectGetMinY(frame) + 15, CGRectGetWidth(frame) - 28, CGRectGetHeight(frame) - 40); //// Abstracted Attributes CGFloat roundedRectangleStrokeWidth = self.borderWidth ; CGFloat roundedRectangleCornerRadius = self.cornerRadius; //// Group { //// Rounded Rectangle Drawing UIBezierPath* roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(CGRectGetMinX(group) + floor(CGRectGetWidth(group) * 0.00060) + 0.5, CGRectGetMinY(group) + floor(CGRectGetHeight(group) * 0.00568) + 0.5, floor(CGRectGetWidth(group) * 0.99940) - floor(CGRectGetWidth(group) * 0.00060), floor(CGRectGetHeight(group) * 0.99432) - floor(CGRectGetHeight(group) * 0.00568)) cornerRadius: roundedRectangleCornerRadius]; CGContextSaveGState(context); CGContextSetShadowWithColor(context, shadowOffset, shadowBlurRadius, shadow.CGColor); [bG setFill]; [roundedRectanglePath fill]; CGContextRestoreGState(context); [borderColor setStroke]; roundedRectanglePath.lineWidth = roundedRectangleStrokeWidth; [roundedRectanglePath stroke]; } } @end 

TitleBannerView是绿色的视图,带有紫色边框。 在此处输入图像描述

首先,IBDesignable可以在预览中看到。

您是否在框架中声明了IBDesignable类? IBInspectable ONLY支持在框架中声明时的预览。

另外,请记住(不是你的情况):

  1. 你的绘图代码应该足够快,你只有100毫秒的绘图时间。

  2. 通常需要prepareForInterfaceBuilder()方法。

IBDesignable仅适用于Interface Builder,但不适用于预览:-(我希望Apple在新的Xcode中修复它…

您是否在界面构建器中显示了一些模拟数据?

使用@ IBDesignable您的初始化程序,布局和绘图方法将用于在canvas上呈现自定义视图

由于在Interface Builder中呈现时自定义视图不具有应用程序的完整上下文,因此您可能需要生成用于显示的模拟数据,例如默认用户配置文件图像或通用天气数据。 有两种方法可以为此特殊上下文添加代码

  • prepareForInterfaceBuilder() :此方法使用其余代码进行编译,但仅在准备好在Interface Builder中显示视图时执行。
  • TARGET_INTERFACE_BUILDER: #if TARGET_INTERFACE_BUILDER预处理器宏将在Objective-C或Swift中工作,以有条件地编译正确的代码

您可能想看一下本教程和示例