gpt4 book ai didi

objective-c - xcode 6 IB_DESIGNABLE- 不从 Interface builder 中的 bundle 加载资源

转载 作者:太空狗 更新时间:2023-10-30 03:10:04 29 4
gpt4 key购买 nike

我正在尝试制作一个自定义控件,使用描述的新 IB_DESIGNABLE 选项在 Interface Builder 中实时更新 here .

- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();

CGRect myFrame = self.bounds;
CGContextSetLineWidth(context, 10);
CGRectInset(myFrame, 5,5);
[[UIColor redColor] set];
UIRectFrame(myFrame);

NSBundle *bundle = [NSBundle mainBundle];
NSString *plistPath;

plistPath = [bundle pathForResource:@"fileExample" ofType:@"plist"];
UIImage *tsliderOff = [UIImage imageNamed:@"btn_slider_off.png"];

[tsliderOff drawInRect:self.bounds];
}

当我在模拟器中运行时,我得到一个红色框,中间是我的图像(正如预期的那样): enter image description here

但是当我尝试使用 Interface Builder 时,它只显示为一个红色框(中间没有图像): Rendered in Interface Builder

当我调试它时:Editor->Debug Selected Views,它显示从包中加载的任何东西都是零。 plistPath 和 tsliderOff 都显示为 nil。

我确保 btn_slider_off.png 包含在 Targets->myFrameWork->Build Phases->Copy Bundle Resources 中。

知道为什么 Interface Builder 在编辑期间看不到 png 文件,但在运行时显示正常吗?如果我无法加载任何要渲染的图像,“创建在 Interface Builder 中呈现的自定义 View ”会有点受限...


根据 rickster 的解决方案进行编辑

rickster 向我指出了解决方案——问题是文件不在 mainBundle 中,它们在 [NSBundle bundleForClass:[self class]] 中;并且 [UIImage imageNamed:@"btn_slider_off.png"] 似乎自动使用了 mainBundle。

下面的代码有效!

#if !TARGET_INTERFACE_BUILDER
NSBundle *bundle = [NSBundle mainBundle];
#else
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
#endif
NSString *fileName = [bundle pathForResource:@"btn_slider_off" ofType:@"png"];
UIImage *image = [UIImage imageWithContentsOfFile:fileName];
[image drawInRect:self.bounds];

最佳答案

截至首次提出此问题时,创建 IB 可设计控件需要将其打包在框架目标中。您不必再这样做了 — 发布的 Xcode 6.0(及更高版本)也将从您的应用程序目标中预览 IB 可设计的控件。但是,问题和解决方案是一样的。

为什么? [NSBundle mainBundle] 返回当前运行的应用程序的主要包。当您从框架调用它时,您会根据正在加载您的框架的应用程序返回不同的包。当您运行您的应用程序时,您的应用程序会加载框架。当您在 IB 中使用该控件时,一个特殊的 Xcode 帮助应用程序会加载该框架。即使您的 IB 可设计控件在您的应用程序目标中,Xcode 也会创建一个特殊的帮助应用程序来运行 IB 内部的控件。

解决方案?改为调用 +[NSBundle bundleForClass:](或 Swift 中的 NSBundle(forClass:))。这将为您提供包含您指定的任何类的可执行代码的包。 (您可以在此处使用 [self class]/self.dynamicType,但请注意,对于不同包中定义的子类,结果会发生变化。)

如果您正在使用框架方法——这对某些应用程序可能很有用,即使 IB 可设计控件不再需要它——最好将图像资源与使用它们的代码放在同一框架中。如果您的框架代码希望使用加载框架的任何应用程序在运行时提供的资源,那么使其可由 IB 设计的最佳做法是伪造它。在您的控件中实现 prepareForInterfaceBuilder 方法,并让它从已知位置(例如框架包或 Xcode 工作区中的静态路径)加载资源。

关于objective-c - xcode 6 IB_DESIGNABLE- 不从 Interface builder 中的 bundle 加载资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24603232/

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