- 论坛徽章:
- 0
|
国内对于 xib嵌套或xib复用的帖子或有效代码很少,但是我仔细查阅了各种资料,最终还是提炼出了一种简单可行的用于实现 xib 的方法与具体实现. 思路见代码注释. 灵感来源于: http://www.maytro.com/2014/04/27 ... nd-auto-layout.html 这个帖子.但是它给的代码,是有问题的,并不能真正实现复用;但思路很有启发性.
示例工程,可直接运行!
用于编写可嵌套的 xib 组件.- /**
- * 可复用组件.用于编写可嵌套的 xib 组件.
- *
- * 适用场景: 需要静态确定布局的页面内的UI元素的复用性问题.
- * 使用方法: 在xib或storyboard中,将某一用于占位的view的 custom class 设为对一个的 component, 则初始化时,会自动使用此component同名的xib文件中的内容去替换对应位置.
- * 注意: 对于可动态确定布局的部分,如tableView中的cell,直接自行从xib初始化即可,不必继承于 MCComponent.
- */
- @interface MCComponent : UIView
-
- @end
复制代码 核心实现文件- #import "MCComponent.h"
-
- @implementation MCComponent
-
- - (instancetype)initWithCoder:(NSCoder *)aDecoder
- {
- self = [super initWithCoder:aDecoder];
-
- if (nil != self) {
- UIView * contentView = [[[NSBundle mainBundle] loadNibNamed: NSStringFromClass([self class]) owner:self options:nil] firstObject];
-
- contentView.translatesAutoresizingMaskIntoConstraints = NO;
- self.translatesAutoresizingMaskIntoConstraints = NO;
-
- [self addSubview: contentView];
-
- [self addConstraint: [NSLayoutConstraint constraintWithItem: contentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem: self attribute:NSLayoutAttributeLeft multiplier: 1.0 constant: 0]];
- [self addConstraint: [NSLayoutConstraint constraintWithItem: contentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem: self attribute:NSLayoutAttributeRight multiplier: 1.0 constant: 0]];
- [self addConstraint: [NSLayoutConstraint constraintWithItem: contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem: self attribute:NSLayoutAttributeTop multiplier: 1.0 constant: 0]];
- [self addConstraint: [NSLayoutConstraint constraintWithItem: contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem: self attribute:NSLayoutAttributeBottom multiplier: 1.0 constant: 0]];
- }
-
- return self;
- }
-
- /*
- // Only override drawRect: if you perform custom drawing.
- // An empty implementation adversely affects performance during animation.
- - (void)drawRect:(CGRect)rect {
- // Drawing code
- }
- */
-
- @end
复制代码 |
|