最近打算使用 Storyboard 开发项目,但某些场景会用到 Storyboard 中引用 Xib,根据网上教程搞了一翻,但由于环境各有差异,按网上教程没弄出来,后来发现可能是 IB 更新的原因,新版 IB 中没有 widthable 和 heightable 属性,所以导致要复用 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;
}
}
网友评论