免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1497 | 回复: 0
打印 上一主题 下一主题

[iOS] iOS xib 嵌套复用 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-10 15:20 |只看该作者 |倒序浏览
国内对于 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
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP