最近打算使用 Storyboard 開(kāi)發(fā)項(xiàng)目,但某些場(chǎng)景會(huì)用到 Storyboard 中引用 Xib,根據(jù)網(wǎng)上教程搞了一翻,但由于環(huán)境各有差異,按網(wǎng)上教程沒(méi)弄出來(lái),后來(lái)發(fā)現(xiàn)可能是 IB 更新的原因,新版 IB 中沒(méi)有 widthable 和 heightable 屬性,所以導(dǎo)致要復(fù)用 Xib 時(shí),AutoLayout 無(wú)效。
自己寫(xiě)了個(gè)基類(lèi)來(lái)解決這個(gè)問(wèn)題, OC 版的項(xiàng)目在 Github 上,點(diǎn)擊前往
pod 'YYNib'
Swift 版本 點(diǎn)擊前往
pod 'YYNib-swift'
兩個(gè)工程中可以使用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;
}
}