我运行的是Xcode 6.1,我已经在很多项目中使用了IB_DESIGNABLE和IBInspectable,但突然之间,它不再起作用了.我创建了子类按钮,将图像和标题垂直居中排列在彼此上方,使用户可以通过IB和IBInspectable设置边框宽度和 colored颜色 .
以下警告已被记录,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
你可能已经注意到它继承了汉堡包.这个基本的汉堡按钮没有图像,它只在按钮周围绘制边框.这个基本的汉堡包按钮有完全相同的问题:它在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上找到该值,这有点奇怪,因为我已经对它进行了子类化.
更新: