IB_DESIGNABLE UIButton 实例渲染失败

IB_DESIGNABLE for UIButton Failed to render instance

我创建了一个分类UIButtonclass,使用IB_DESIGNABLE。但是我得到了一个奇怪的错误 Failed to render instance of RoundedCornerButton: Rendering the view took longer than 200 ms. Your drawing code may suffer from slow performance. 我在这个网站上尝试了很多建议,但仍然无法修复它。请帮我找到根cause.Please更多细节见图片(RoundedCornerButton:是UIButton的类别class)

更新RoundedCornerButton class的代码:

.h 文件

  #import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface RoundedCornerButton : UIButton
@property (nonatomic) IBInspectable int cornerRadius;
@property (nonatomic) IBInspectable int borderWidth;
@property (nonatomic) IBInspectable UIColor* borderColor;
@end

.m 文件:

  #import "RoundedCornerButton.h"

@implementation RoundedCornerButton

-(void)drawRect:(CGRect)rect{
    self.layer.borderWidth = self.borderWidth;
    self.layer.borderColor = self.borderColor.CGColor;
    [self.layer setCornerRadius:self.cornerRadius];
    self.clipsToBounds = YES;

}
@end

我可以运行我的项目在设备上成功,但是我得到了上面的红色警告。(所以奇怪,我用的是Xcode 7.0)

你不能在 drawRect 中那样玩你的 layer。那不是画画!绘画是关于内容的。

将该代码移至其他位置,例如 awakeFromNibprepareForInterfaceBuilder(两者),一切都会好起来的。

示例代码如下:

@implementation RoundedCornerButton

-(void) config {
    self.layer.borderWidth = self.borderWidth;
    self.layer.borderColor = self.borderColor.CGColor;
    [self.layer setCornerRadius:self.cornerRadius];
    self.clipsToBounds = YES;
}

-(void)prepareForInterfaceBuilder {
    [self config];
}

-(void)awakeFromNib {
    [super awakeFromNib];
    [self config];
}

@end

您可以在 Xcode 7:

中看到它在 IB 中运行良好