4

我有许多用笔尖设计的可重用视图,它们都是 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 文件中,我将文件的所有者设置为 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
}

任何想法?

4

1 回答 1

3

我知道这个问题很老,但我有一个类似的问题,并且由于 Objective C 的例子不多,我想分享我的解决方案。

您在 Objective C 中使用的代码与在 SWIFT 中使用的代码不同。在 Objective C 中,您尝试访问主包,但是当尝试在 IB 中加载视图时,没有主包。这段代码对我有用:

NSBundle *bundle = [NSBundle bundleForClass:self.classForCoder];
self.view = [[bundle loadNibNamed:@"HighscoreLabelView" owner:self options:nil] objectAtIndex:0];
于 2019-03-17T21:00:11.467 回答