最近打算使用 Storyboard 開發(fā)項目,但某些場景會用到 Storyboard 中引用 Xib蝌借,根據(jù)網(wǎng)上教程搞了一翻嘱支,但由于環(huán)境各有差異,按網(wǎng)上教程沒弄出來厕九,后來發(fā)現(xiàn)可能是 IB 更新的原因蓖捶,新版 IB 中沒有 widthable 和 heightable 屬性,所以導(dǎo)致要復(fù)用 Xib 時扁远,AutoLayout 無效俊鱼。
自己寫了個基類來解決這個問題, OC 版的項目在 Github 上穿香,點擊前往
pod 'YYNib'
Swift 版本 點擊前往
pod 'YYNib-swift'
兩個工程中可以使用Pod引入亭引,注意: 如果需要支持 iOS7 的話,swift 版本不能使用 Pod 引入皮获。
OC主要代碼如下
#import "YYNibView.h"
@implementation YYNibView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self initSubviews];
if (CGRectIsEmpty(frame)) {
self.frame = _contentView.bounds;
} else {
_contentView.frame = self.bounds;
}
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self initSubviews];
_contentView.frame = self.bounds;
}
return self;
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
_contentView.frame = self.bounds;
}
- (void)setBackgroundColor:(UIColor *)backgroundColor {
[super setBackgroundColor:backgroundColor];
_contentView.backgroundColor = backgroundColor;
}
- (void)initSubviews {
NSString *className = NSStringFromClass([self class]);
_contentView = [[NSBundle mainBundle] loadNibNamed:className owner:self options:nil].firstObject;
_contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self addSubview:_contentView];
// Fix backgroundColor
self.backgroundColor = _contentView.backgroundColor;
}
@end
Swift 主要代碼如下
import UIKit
class YYNibView: UIView {
var contentView:UIView!;
override init(frame: CGRect) {
super.init(frame: frame);
self.initWithSubviews();
if (CGRectIsEmpty(frame)) {
self.frame = (contentView?.bounds)!;
} else {
contentView?.frame = self.bounds;
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
self.initWithSubviews();
self.contentView?.frame = self.bounds;
}
override var frame: CGRect {
didSet {
self.contentView?.frame = self.bounds;
}
}
override var backgroundColor: UIColor? {
didSet {
self.contentView?.backgroundColor = self.backgroundColor;
}
}
func initWithSubviews() {
let className = "\(self.classForCoder)"
self.contentView = NSBundle.mainBundle().loadNibNamed(className, owner: self, options: nil).first as? UIView;
self.contentView?.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight];
self.addSubview(self.contentView!);
// Fix backgroundColor
self.backgroundColor = self.contentView?.backgroundColor;
}
}