1 前言
Xcode中整合的BI中的控制項十分豐富,但有時候難免不能滿足我們的需求,今天我們來學習一下如何使用XIB自訂一個UIView,做到複用的作用。
2 詳細流程
目錄檢視:
2.1 建立一個single view application類型的iOS application工程,名字取為CustomView,如,我們不往CustomViewViewController.xib中添加任何控制項
2.2 建立一個CustomView.xib,過程如下:
然後往介面上拖一個label和一個button:
2.3修改View視圖的屬性:
去掉Autolayout:
設定Size為Freeform,設定背景顏色:
2.4 設定ZYViewController.xib中的View的Size屬性為None:
ZYViewController.m代碼:
[plain] - (void)viewDidLoad
{
[super viewDidLoad];
//獲得nib視圖數組
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"CustomView" owner:self options:nil];
//得到第一個UIView
UIView *tmpCustomView = [nib objectAtIndex:0];
//獲得螢幕的Frame
CGRect tmpFrame = [[UIScreen mainScreen] bounds];
//設定自訂視圖的中點為螢幕的中點
[tmpCustomView setCenter:CGPointMake(tmpFrame.size.width / 2, tmpFrame.size.height / 2)];
//添加視圖
[self.view addSubview:tmpCustomView];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//獲得nib視圖數組
NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"CustomView" owner:self options:nil];
//得到第一個UIView
UIView *tmpCustomView = [nib objectAtIndex:0];
//獲得螢幕的Frame
CGRect tmpFrame = [[UIScreen mainScreen] bounds];
//設定自訂視圖的中點為螢幕的中點
[tmpCustomView setCenter:CGPointMake(tmpFrame.size.width / 2, tmpFrame.size.height / 2)];
//添加視圖
[self.view addSubview:tmpCustomView];
}
運行結果: