IOS開發(97)之自訂視圖之使用XIB自訂一個UIView

來源:互聯網
上載者:User

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];
   
}
運行結果:

 
 


 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.