- 論壇徽章:
- 0
|
國(guó)內(nèi)對(duì)于 xib嵌套或xib復(fù)用的帖子或有效代碼很少,但是我仔細(xì)查閱了各種資料,最終還是提煉出了一種簡(jiǎn)單可行的用于實(shí)現(xiàn) xib 的方法與具體實(shí)現(xiàn). 思路見(jiàn)代碼注釋. 靈感來(lái)源于: http://www.maytro.com/2014/04/27 ... nd-auto-layout.html 這個(gè)帖子.但是它給的代碼,是有問(wèn)題的,并不能真正實(shí)現(xiàn)復(fù)用;但思路很有啟發(fā)性.
示例工程,可直接運(yùn)行!
用于編寫可嵌套的 xib 組件.- /**
- * 可復(fù)用組件.用于編寫可嵌套的 xib 組件.
- *
- * 適用場(chǎng)景: 需要靜態(tài)確定布局的頁(yè)面內(nèi)的UI元素的復(fù)用性問(wèn)題.
- * 使用方法: 在xib或storyboard中,將某一用于占位的view的 custom class 設(shè)為對(duì)一個(gè)的 component, 則初始化時(shí),會(huì)自動(dòng)使用此component同名的xib文件中的內(nèi)容去替換對(duì)應(yīng)位置.
- * 注意: 對(duì)于可動(dòng)態(tài)確定布局的部分,如tableView中的cell,直接自行從xib初始化即可,不必繼承于 MCComponent.
- */
- @interface MCComponent : UIView
-
- @end
復(fù)制代碼 核心實(shí)現(xiàn)文件- #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
復(fù)制代碼 |
|