大鐘的ios開發之旅(4)————簡單談談ios程式介面實現的三種方式(代碼建立,xib和storyboard)

來源:互聯網
上載者:User

標籤:ios開發   介面   ios   uiviewcontroller   xcode   

/********************************************************************************************
 * author:[email protected]大鐘                                                                                                                          
 * E-mail:[email protected]

 *site:http://www.idealpwr.com/  

 *深圳市動力思維科技發展有限公司                                                                                                         
 * http://blog.csdn.net/conowen                                                                                                              
 * 註:本文為原創,僅作為學習交流使用,轉載請標明作者及出處。     

 ********************************************************************************************/


一丶前言

       實現ios介面總的來說,有三種方式,傳統的是純程式碼建立與xib建立,近年來,蘋果官網一直推薦用storyboard管理項目介面,最新的xcode建立的project也是預設為storyboard方式了。相對於Android開發而已,介面的管理就兩種方式,一種是純程式碼,另外一種技術XML布局方式。其實ios與Android的介面管理相同點挺多的,下面就分開說說。


二、純程式碼建立

 首先如下,純程式碼建立一個UIImageView,並給它設定圖片,並且根據裝置的不同,動態設定其位置座標與長寬。


    UIImageView *food=[[UIImageView alloc] init];    food.image=[UIImage imageNamed:_imgName];    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {        food.frame=CGRectMake((width*0.25+width/2-197*4/6),height+height/2, 197*4/3, 260*4/3);    }    else{        food.frame=CGRectMake((width*0.25+width/2-90*4/6),height+height/2, 90*4/3, 118*4/3);        }

優點:可以靈活地適應各種環境,無論是什麼ios版本,或者iPhone,ipad,都可以動態地適應各種情境。

缺點:代碼量大,構建控制項麻煩,點擊的監聽函數和delegate要自己手動建立。


三、xib方式建立

       xib建立視圖,就如同Android的XML一樣,但是它比Android的XML方式還強大。可以直接設定控制項的監聽函數與delegate,控制項的各種屬性基本都能設定。


3.1、xib項目的初始化寫法

     使用xib的項目,AppDelegate的didFinishLaunchingWithOptions方法中一般這麼寫。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];        UINavigationController *navController;    HomeViewController *homeViewControl;    if (IS_IPAD) {                homeViewControl = [[HomeViewController alloc] initWithNibName:@"HomeViewController_iPad" bundle:nil];            }    else{        homeViewControl = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];            }            navController = [[UINavigationController alloc] initWithRootViewController:homeViewControl];    self.window.rootViewController =navController;        // Override point for customization after application launch.    self.window.backgroundColor = [UIColor whiteColor];    [self.window makeKeyAndVisible];    return YES;}


3.2、綁定xib到代碼檔案

     建立一個xib檔案,然後按照如與.m檔案綁定。

     點擊File,s Owner,在右邊的Custom Class輸出要綁定的.m檔案即可。一般這個.m檔案是一個繼承UIViewController的類。



3.3、xib檔案助手的使用


      建立聯絡之後,可以在右邊的控制項欄目中拖拽控制項到xib檔案中。然後可以點擊xcode右上方的show the Assistant editor,開啟xib助手編輯器如。



按住鍵盤的ctrl鍵,拖拽到綁定的m檔案對應的h檔案中。就可以聲明這個控制項。





在xib助手邊界器介面。右邊介面選擇m檔案,按住鍵盤的ctrl鍵,拖拽控制項到右邊m檔案中,就可以快速實現這個控制項的點擊監聽函數。如。






3.4、xib方式實現delegate

     對於一些tableview或者UICollectionView,可以直接右鍵這個控制項,然後拖拽dataSource到Files Owner,就可以實現dataSource與delegate函數。不必在.h檔案寫。



 建立一個帶xib的viewcontroller,實現跳轉。

            FunViewController *funViewController;                        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {                                funViewController = [[FunViewController alloc] initWithNibName:@"FunViewController_iPad" bundle:nil];                            }            else{                funViewController = [[FunViewController alloc] initWithNibName:@"FunViewController" bundle:nil];                            }                        [self.navigationController pushViewController:funViewController animated:YES];

3.5、xib檔案的本質

    其實xib檔案就是一個xml檔案,右鍵xib檔案,用source code方式開啟就可以看到裡面的內容了。

<?xml version="1.0" encoding="UTF-8" standalone="no"?><document type="com.apple.InterfaceBuilder3.CocoaTouch.iPad.XIB" version="3.0" toolsVersion="6250" systemVersion="13F34" targetRuntime="iOS.CocoaTouch.iPad" variant="6xAndEarlier" propertyAccessControl="none">    <dependencies>        <deployment identifier="iOS"/>        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6244"/>    </dependencies>    <objects>        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="HomeViewController">            <connections>                <outlet property="bt1" destination="bff-VE-ebG" id="JOH-p4-R0X"/>                <outlet property="bt2" destination="g7d-fl-SYA" id="tzh-X9-DgX"/>                <outlet property="bt3" destination="obZ-WC-iEz" id="KnU-g6-StI"/>                <outlet property="bt4" destination="Ygr-Nd-5hI" id="0hk-jV-3OP"/>                <outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>            </connections>        </placeholder>        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>        <view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">            <rect key="frame" x="0.0" y="20" width="768" height="1004"/>            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>            <subviews>                <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="middleTruncation" id="bff-VE-ebG">                    <rect key="frame" x="20" y="53" width="360" height="429"/>                    <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>                    <inset key="insetFor6xAndEarlier" minX="0.0" minY="44" maxX="0.0" maxY="-44"/>                    <state key="normal" title="Button" image="app1.png">                        <color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>                    </state>                    <connections>                        <action selector="bt1Action:" destination="-1" eventType="touchUpInside" id="AKz-Lb-p87"/>                    </connections>                </button>                            </subviews>            <color key="backgroundColor" red="0.0" green="0.80000000000000004" blue="0.81960784313724999" alpha="1" colorSpace="calibratedRGB"/>            <simulatedStatusBarMetrics key="simulatedStatusBarMetrics"/>        </view>    </objects>    <resources>        <image name="app1.png" width="492" height="587"/>        <image name="app2.png" width="492" height="587"/>        <image name="app3.png" width="492" height="587"/>        <image name="app4.png" width="492" height="587"/>    </resources>    <simulatedMetricsContainer key="defaultSimulatedMetrics">        <simulatedStatusBarMetrics key="statusBar" statusBarStyle="blackOpaque"/>        <simulatedOrientationMetrics key="orientation"/>        <simulatedScreenMetrics key="destination"/>    </simulatedMetricsContainer></document>


3.6、把iPhone版本的xib更改為ipad版本

用source code方式開啟iPhone版本的xib,copy代碼覆蓋到建立的xib檔案中。

在檔案頭

<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6250" systemVersion="13F34" targetRuntime="iOS.CocoaTouch" variant="6xAndEarlier" propertyAccessControl="none">

更改為以下的,就是添加兩個iPad標記

<document type="com.apple.InterfaceBuilder3.CocoaTouch.iPad.XIB" version="3.0" toolsVersion="6250" systemVersion="13F34" targetRuntime="iOS.CocoaTouch.iPad" variant="6xAndEarlier" propertyAccessControl="none">

優點:每個viewcontroller對應單獨的xib,可以更加方便單獨管理,項目也方便多人一起開發,改動視圖方便,不用全域改動。

缺點:項目大的話,xib檔案過多,不容易統一管理。跳轉只能在代碼實現,比較混亂。


四、storyboard方式


    storyboard方式是ios5之後Apple提供了一種全新的方式。簡單來說,StoryBoard是一個包含了多個xib與xib之間跳轉關係的檔案。在StoryBoard中不僅可以看到每個ViewController的配置樣式,也可以知道各個ViewController之間的轉換關係。最近版本的xcode建立的工程都是預設以storyboard方式。可見未來的發展趨勢都是storyboard布局方式。

使用storyboard布局的項目 AppDelegate方法中幾乎沒有內容。

使用執行個體:
建立一個single view項目,把自動產生的storyboard檔案刪除。自己再重新建立一個storyboard檔案。在項目的targets裡面做如下設定


這樣項目啟動的時候,就會自動載入這個storyboard檔案,不用自己代碼配置。

開啟自己建立的storyboard檔案。拉一個Navigation Controller到裡面去。這一步的操作,系統也同時幫你建立了一個Table View,點擊Navigation Controller在右邊的屬性欄中的Is Initial View Controller中勾選上。表示這個是初始的Viewcontroller。


把系統幫你建立的那個Table View刪除,自己在右邊拖一個普通的View Controller到storyboard檔案中,在這個建立的View Controller雙擊一下上面的標題列,然後在custom那裡綁定自己需要綁定的viewcontroller 代碼檔案。然後按住ctrl鍵,把Navigation Controller拖拽到建立的View Controller那裡,彈出來的對話方塊,設定為root view controller


可以設定這個view controller的title之類的,如。




再建立一個View Controller,同樣步驟綁定一個.m檔案。拖動一個button到第一個View Controller,然後按住ctrl鍵,先第二個View Controller拖拽。彈出的對話方塊中選擇show,就可以實現點擊button跳轉到第二個View Controller的操作。



優點:所有xib集中在一個storyboard檔案中,管理方便,View Controller跳轉很輕鬆就可以實現,大大減少代碼量。
缺點:由於所有xib都集中在一個檔案中,對於一些大型項目,分工起來就比較困難,不好分工,而且採用storyboard方式對系統資源的耗費比代碼和xib方式要大。


五、總結

     對於個人而言,我比較偏向於xib為主要的視圖構建方式,代碼建立為輔助,因為我是從Android開發轉到ios開發,比較習慣於每一個activity 對應一個xml布局檔案這樣的方式,xib也能滿足我的需要,目前,暫且是這樣使用,等工程需要,在使用storyboard方式,畢竟這是未來的發展趨勢。



大鐘的ios開發之旅(4)————簡單談談ios程式介面實現的三種方式(代碼建立,xib和storyboard)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.