ios - 如何使用 IB_DESIGNABLE 在 Storyboard中可视化可重用的 xib?

标签 ios xcode interface-builder xcode9.2

我想在 Xcode 9.2 中使用 IB_DESIGNABLE 常量在 Storyboard中可视化 XIB, objective-c 目标为 iOS SDK 11.2。

根据this article来自 Apple 的 prepareForInterfaceBuilder 方法由 Interface Builder 调用,让您可以做任何只能为 Interface Builder 做的事情。

When Interface Builder instantiates a class with the IB_DESIGNABLE attribute, it calls this method to let the resulting object know that it was created at design time. You can implement this method in your designable classes and use it to configure their design-time appearance.

基于此article我想在 Storyboard中可视化 XIB。当我在 ViewController 上使用 UIView 元素并设置

  • 首先将自定义类添加到 XibView
  • 第二个 nibName 属性到 MainViewController,XIB 文件的名称

我收到以下构建时错误:

Main.storyboard:
error: IB Designables: 
Failed to render and update auto layout status for MainViewController (8zi-kg-fjR):
The agent threw an exception.

我在 Main.storyboard 中使用的 View 中收到此错误而不是可视化 XIB,我做错了什么?

这是XibView.h

IB_DESIGNABLE
@interface XibView : UIView
@property (nonatomic, strong) IBOutlet UIView* contentView;
@property (nonatomic) IBInspectable NSString* nibName;
@end

这是XibView.m

#import "XibView.h"

@implementation XibView

- (id)initWithCoder:(NSCoder *) coder
{
    self = [super initWithCoder: coder];
    if (self)
    {
        [self xibSetup];
    }
    return self;
}

//---------------------------------------------------------------------

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self xibSetup];
    }
    return self;
}

//---------------------------------------------------------------------

- (void)prepareForInterfaceBuilder
{
    [super prepareForInterfaceBuilder];
    [self xibSetup];
}

//---------------------------------------------------------------------

- (void)xibSetup
{
    [[NSBundle mainBundle] loadNibNamed:_nibName owner:nil options:nil];
    [self addSubview:self.contentView];
    self.contentView.frame = self.bounds;
}

@end

最佳答案

这是我认为有错误的方法:

- (void)xibSetup
{
    [[NSBundle mainBundle] loadNibNamed:_nibName owner:nil options:nil];
    [self addSubview:self.contentView];
    self.contentView.frame = self.bounds;
}

nib 加载器无法设置 self.contentView 因为您没有将 self 作为 owner 参数传递给 loadNibNamed :选项:。试试这个:

    [[NSBundle mainBundle] loadNibNamed:_nibName owner:self options:nil];

关于ios - 如何使用 IB_DESIGNABLE 在 Storyboard中可视化可重用的 xib?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52544047/

相关文章:

ios - 在组合中使用 Future 接收取消事件

ios - 快速填充 TableView

IOS推送许多没有弹出的 View Controller

ios - 我可以以编程方式设置环境变量吗?

ios - 将容器的来源设置为另一个容器的问题(Swift 4.2)

iOS9:自定义UIWindow让状态栏消失

ios - 当我想运行自己的应用程序 iOS9 时无法在 iPhone 上验证应用程序

xcode - 如何在不启动 Xcode 的情况下运行 iPhone 模拟器?

ios - 如何将 UILabel 与 UIViewController 的角对齐

ios - 在 Swift 中调整 UIWebview 的高度/宽度