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