IBDesignable无法在Objective-C中使用

问题描述 投票:2回答:1

我有许多使用nib设计的可重用视图,它们都是类NibView的子类

class NibView: UIView {

var view: UIView!

func setupNib(nibName:String) {
    view = loadViewFromNib(nibName)
    view.frame = bounds
    view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
    addSubview(view)
}

func loadViewFromNib(nibName:String) -> UIView {
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: nibName, bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
    return view
}

}

我是这样的子类

@IBDesignable class ExampleView: NibView {

@IBOutlet weak var label: UILabel!

private var _property:Int = 0
@IBInspectable var property:Int {
    set {
        _property = newValue
        label.text = "\(newValue)"
    } get {
        return _property
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

func setup() {
    setupNib("ExampleView")
}

override func layoutSubviews() {
    super.layoutSubviews()
    // custom init

}
}

在NIB文件中,我将File的所有者设置为ExampleView。一切都很完美,故事板和xib都可以实现一切。

现在,在Objective-C中做同样的事情是行不通的

IB_DESIGNABLE

@interface ExampleView : NibView

@property (nonatomic) IBInspectable NSUInteger count;

@end


@implementation NibView

- (void)setupNib:(NSString *)nibName {
    self.view = [self loadViewFromNib:nibName];
    self.view.frame = self.bounds;
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:self.view];
}

- (UIView *)loadViewFromNib:(NSString *)nibName {
    UIView *view = [[[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil] objectAtIndex:0];
    return view;
}

@end

@implementation ExampleView

- (id)init {
     self = [super init];
     if(self) {
        [self setup];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
     self = [super initWithFrame:frame];
     if(self) {
        [self setup];
    }
     return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
     self = [super initWithCoder:aDecoder];
     if(self) {
        [self setup];
    }
     return self;

}

- (void)setup {
    [self setupNib:@"ExampleView"];
     // Custom init
}

任何的想法?

objective-c swift xib ibdesignable ibinspectable
1个回答
1
投票

我知道这个问题已经过时了,但是我遇到了类似的问题,因为目标C没有很多例子,我想分享我的解决方案。

您没有像在SWIFT中那样在Objective C中使用相同的代码。在Objective C中,您尝试访问主捆绑包,但在尝试加载IB中的视图时,没有主捆绑包。这段代码对我有用:

NSBundle *bundle = [NSBundle bundleForClass:self.classForCoder];
self.view = [[bundle loadNibNamed:@"HighscoreLabelView" owner:self options:nil] objectAtIndex:0];
© www.soinside.com 2019 - 2024. All rights reserved.