如何在Objective-C中设置IBInspectable的默认值?

Can*_*ğlu 63 xcode objective-c interface-builder swift ibinspectable

我知道IBInspectable-properties的默认值可以设置为:

@IBInspectable var propertyName:propertyType = defaultValue在斯威夫特.但是我如何在Objective-C中实现类似的效果,以便我可以在Interface Builder中将某些属性的默认值设置为某些属性?

rin*_*aro 56

由于IBInspectable值是在initWithCoder:之前和之后awakeFromNib:设置的,因此可以在initWithCoder:方法中设置默认值.

@interface MyView : UIView
@property (copy, nonatomic) IBInspectable NSString *myProp;
@property (assign, nonatomic) BOOL createdFromIB;
@end

@implementation MyView

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self != nil) {
        self.myProp = @"foo";
        self.createdFromIB = YES;
    }
    return self;
}

- (void)awakeFromNib {
    if (self.createdFromIB) {
        //add anything required in IB-define way
    }
    NSLog(@"%@", self.myProp);
}

@end
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,但我实际上正在寻找一种让IB看到价值观的方法.那可能吗? (11认同)
  • 谢谢你的回答!此外,为了查看故事板中的使用含义,您需要实现`- (void)prepareForInterfaceBuilder`,它将使用可检查值来呈现内容 (3认同)
  • 你刚刚保存了我的培根@rintaro.我试图在`initWithCoder:`期间使用来自IBInspectables的值设置我的自定义控件,并且无法弄清楚为什么它们都是零.现在我在`awakeFromNib`中设置我的自定义控件,一切都很好.谢谢! (2认同)