Chinaunix

标题: iOS xib 嵌套复用 [打印本页]

作者: ewen321    时间: 2015-07-10 15:20
标题: iOS xib 嵌套复用
国内对于 xib嵌套或xib复用的帖子或有效代码很少,但是我仔细查阅了各种资料,最终还是提炼出了一种简单可行的用于实现 xib 的方法与具体实现. 思路见代码注释. 灵感来源于:  http://www.maytro.com/2014/04/27 ... nd-auto-layout.html 这个帖子.但是它给的代码,是有问题的,并不能真正实现复用;但思路很有启发性.
示例工程,可直接运行!

用于编写可嵌套的 xib 组件.
  1. /**
  2. *  可复用组件.用于编写可嵌套的 xib 组件.
  3. *  
  4. *  适用场景: 需要静态确定布局的页面内的UI元素的复用性问题.
  5. *  使用方法: 在xib或storyboard中,将某一用于占位的view的 custom class 设为对一个的 component, 则初始化时,会自动使用此component同名的xib文件中的内容去替换对应位置.
  6. *  注意: 对于可动态确定布局的部分,如tableView中的cell,直接自行从xib初始化即可,不必继承于 MCComponent.
  7. */
  8. @interface MCComponent : UIView

  9. @end
复制代码
核心实现文件
  1. #import "MCComponent.h"

  2. @implementation MCComponent

  3. - (instancetype)initWithCoder:(NSCoder *)aDecoder
  4. {
  5.     self = [super initWithCoder:aDecoder];
  6.      
  7.     if (nil != self) {
  8.         UIView * contentView = [[[NSBundle mainBundle] loadNibNamed: NSStringFromClass([self class]) owner:self options:nil] firstObject];
  9.          
  10.         contentView.translatesAutoresizingMaskIntoConstraints = NO;
  11.         self.translatesAutoresizingMaskIntoConstraints = NO;
  12.          
  13.         [self addSubview: contentView];
  14.          
  15.         [self addConstraint: [NSLayoutConstraint constraintWithItem: contentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem: self attribute:NSLayoutAttributeLeft multiplier: 1.0 constant: 0]];
  16.         [self addConstraint: [NSLayoutConstraint constraintWithItem: contentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem: self attribute:NSLayoutAttributeRight multiplier: 1.0 constant: 0]];
  17.         [self addConstraint: [NSLayoutConstraint constraintWithItem: contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem: self attribute:NSLayoutAttributeTop multiplier: 1.0 constant: 0]];
  18.         [self addConstraint: [NSLayoutConstraint constraintWithItem: contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem: self attribute:NSLayoutAttributeBottom multiplier: 1.0 constant: 0]];
  19.     }
  20.      
  21.     return self;
  22. }

  23. /*
  24. // Only override drawRect: if you perform custom drawing.
  25. // An empty implementation adversely affects performance during animation.
  26. - (void)drawRect:(CGRect)rect {
  27.     // Drawing code
  28. }
  29. */

  30. @end
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2