我們知道如何使用XIB自定義一個UIView, 但當(dāng)將其添加到AutoLayout的VC上時, 如何使這個自定義的UIView也可以跟隨父VC 使用Autolayout呢? 下面細(xì)細(xì)道來..
1,新建一個文件 “File -> New -> New File” (cmd + N), 選擇 “Cocoa Touch” 然后是 “Objective-C class”,“UIView”的子類, 輸入文件名:TestCustomView
2,新建一個 “User Interface” 然后是 “View”.命名為: TestCustomView
3,設(shè)置xib 的file's owner 為你自定義的類

set.jpg
4,然后打開TestCustomView.h添加一個IBOutlet
<pre><code>
@property (nonatomic, weak) IBOutlet UIView *view;
</code></pre>
5,將此IBOutlet 連接到TestCustomView.xib 的View

oulet.jpg
6,最后打開TestCustomView.m,添加如下代碼:
<pre><code>
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
NSString *className = NSStringFromClass([self class]);
self.view = [[[NSBundle mainBundle] loadNibNamed:className owner:self options:nil] firstObject];
[self addSubview:self.view];
return self;
}
return nil;
}
</code></pre>
在VC中使用它:

use.jpg
附個demo:
https://github.com/wangjianlewo/TestCustomViewFromXib
demo 中 右邊的按鈕總是距離屏幕的最右方10