gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:32:00 25 4
gpt4 key购买 nike

我想在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com