【发布时间】:2014-12-26 16:40:48
【问题描述】:
我正在运行 Xcode 6.1,并且我已经在很多项目中使用 IB_DESIGNABLE 和 IBInspectable,但突然之间它就不再工作了。我创建了子类按钮,这些按钮将图像和标题垂直居中排列,并允许用户通过 IB 使用 IBInspectable 设置边框宽度和颜色。
记录了以下警告,并且在 drawRect 中没有可用的代码预览:
warning: IB Designables: Ignoring user defined runtime attribute for key path "spacingBetweenLabelAndImage" on instance of "UIButton". Hit an exception when attempting to set its value: [<UIButton 0x7f9278591260> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key spacingBetweenLabelAndImage.
不过,它呈现的运行时就像我希望它呈现的那样,它还尊重我通过 IB 添加的相同自定义间距。
这是重新排列按钮和标题的菜单按钮的代码:
#import "HamburgerButton.h"
IB_DESIGNABLE
@interface HamburgerImageButton : HamburgerButton
@property IBInspectable CGFloat spacingBetweenLabelAndImage;
@end
实施:
#import "HamburgerImageButton.h"
@implementation HamburgerImageButton
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
CGSize imageSize = self.imageView.frame.size;
CGSize titleSize = self.titleLabel.frame.size;
// Move the label left and the image right by half the width
CGFloat leftInset = titleSize.width / 2;
CGFloat rightInset = imageSize.width / 2;
CGFloat halfSpacing = self.spacingBetweenLabelAndImage == 0 ? 0 : self.spacingBetweenLabelAndImage / 2;
CGFloat topInset = imageSize.height / 2 + halfSpacing;
CGFloat bottomInset = titleSize.height / 2 + halfSpacing;
UIEdgeInsets imageInsets = UIEdgeInsetsMake(-bottomInset, leftInset, bottomInset, -leftInset);
UIEdgeInsets titleInsets = UIEdgeInsetsMake(topInset, -rightInset, -topInset, rightInset);
self.imageEdgeInsets = imageInsets;
self.titleEdgeInsets = titleInsets;
}
@end
您可能已经注意到它继承了 HamburgerButton。这个基本的汉堡按钮没有图像,它只在按钮周围绘制边框。这个基本的汉堡按钮有完全相同的问题:它没有在 IB 的 drawRect 中绘制它的边框并且它有相同类型的错误。为了完整起见,这是该代码:
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface HamburgerButton : UIButton
@property IBInspectable CGFloat borderWidth;
@property IBInspectable UIColor *borderColor;
@end
实施:
#import "HamburgerButton.h"
#import <QuartzCore/QuartzCore.h>
@implementation HamburgerButton
- (void)copyInspectables {
self.layer.borderWidth = self.borderWidth;
self.layer.borderColor = self.borderColor.CGColor;
}
- (void)drawRect:(CGRect)rect {
[self copyInspectables];
}
@end
我真的不明白为什么它只是发出警告而没有别的。我并没有真正改变我所做的。我检查了故事板,它是 iOS 7 及更高版本,旨在在 Xcode 6(最新)中运行。
它抱怨无法在 UIButton 上找到该值,这有点奇怪,因为我已经对它进行了子类化。
更新: 所以我改变了周围的一切,它奏效了。现在它再次出现,没有改变任何其他东西。我认为 Xcode 6.1 中存在错误...:/
【问题讨论】:
-
请注意,(2017) 在某些情况中,通过单击“编辑器 -> 刷新所有视图”并让它完全运行即可非常简单地解决此问题.请注意,这些天(2017 年)当然基本上不可能使用 Xcode,除非您使用“关闭自动刷新”技巧...explanation...特别是如果您这样做,您有时会收到警告问题在这里,你只需要“刷新”并让它运行。
标签: ios objective-c uibutton interface-builder xcode6