Dazhong's ios development journey (4) ---- three methods for implementing the ios Program Interface (code creation, xib and storyboard) and xibstoryboard

Source: Internet
Author: User

Dazhong's ios development journey (4) ---- three methods for implementing the ios Program Interface (code creation, xib and storyboard) and xibstoryboard

/*************************************** **************************************** *************
* Author: conowen @ Dazhong
* E-mail: conowen@hotmail.com

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

* Shenzhen power thinking Technology Development Co., Ltd.
* Http://blog.csdn.net/conowen
* Note: This article is original and only used for learning and communication. For more information, indicate the author and its source.

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


1. Preface

There are three methods to implement the ios interface. The traditional method is code-only creation and xib creation. In recent years, the apple official website has always recommended using storyboard to manage the project interface, the new project created by xcode is also created by default in the storyboard mode. Compared with Android development, there are two ways to manage the interface: one is pure code and the other is XML layout. In fact, there are many similarities in interface management between ios and Android. Let's talk about it separately.


Ii. Code-only Creation

First, create a UIImageView in the following code, set the image for it, and dynamically set the coordinates and length and width of the Image Based on the device.


    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);        }

Advantages: It can be flexibly adapted to various environments, No matter what ios version, or iPhone or ipad, it can dynamically adapt to various scenarios.

Disadvantage: the large amount of code makes building controls troublesome. You need to manually create the listening function and delegate.


Iii. xib Creation

Xib creates a view, just like Android XML, but it is more powerful than Android XML. You can directly set the monitoring function and delegate of the control. All the attributes of the control can be set.


3.1 initialize the xib Project

This is generally the case in the didfinishlaunchingwitexceptions method of AppDelegate when xib is used.

- (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 bind xib to the code file

Create an xib file and bind it to The. m file as shown in.

Click File, s Owner, and output the. m File to be bound in m Class on the right. Generally, this. m file is a class that inherits UIViewController.



3.3 Use of xib file assistant


After creating a contact, you can drag the control to the xib file in the control column on the right. Click show the Assistant editor in the upper-right corner of xcode to open the xib Assistant editor, as shown in.



Press and hold the ctrl key on the keyboard and drag it to the H file corresponding to the bound m file. You can declare this control.





In the xib assistant boundary interface. Select the m file on the right interface, press and hold the ctrl key on the keyboard, and drag the control to the m file on the right to quickly implement the click listening function of this control. For example.






3.4. Implement delegate in xib Mode

For some tableview or UICollectionView, right-click the control and drag dataSource to the Files Owner to implement the dataSource and delegate functions. Do not write in. h file.



Create a new viewcontroller with xib for redirection.

            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. Nature of xib files

In fact, the xib file is an xml file. Right-click the xib file and open it in source code mode to see the content in it.

<?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. Change the iPhone xib to the ipad version.

Use the source code method to open the iPhone version xib, and copy the code to overwrite the new xib file.

In the file header

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

To add two iPad tags

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

Advantages: Each viewcontroller corresponds to a separate xib, which makes it easier to manage the project separately and facilitates development by multiple people. It is convenient to change the view without making global changes.

Disadvantages: if the project is large, there are too many xib files and it is not easy to manage them in a unified manner. Redirection can only be implemented in the code, which is confusing.


Iv. storyboard Mode


The storyboard method is a completely new method provided by Apple after ios5. Simply put, StoryBoard is a file that contains multiple jump relationships between xib and xib. On the StoryBoard, you can not only view the layout style of each ViewController, but also know the Conversion Relationship between each ViewController. In the latest version of xcode, all new projects are created in the storyboard mode by default. It can be seen that the future development trend is the layout of storyboard.

There is almost no content in the AppDelegate method of the project that uses the storyboard layout.

Instance used:
Create a single view project and delete the automatically generated storyboard file. Create a new storyboard file. Make the following settings in the targets of the project:


In this way, the storyboard file is automatically loaded when the project is started, and you do not need to configure your own code.

Open the storyboard file you created. Pull a Navigation Controller to it. In this step, the system also creates a new Table View for you. Click "Is Initial View Controller" in the property bar on the right to select "Navigation Controller. This is the initial Viewcontroller.


Delete the Table View that is created by the system. Drag a common View Controller to the storyboard file on the right and double-click the title bar on the newly created View Controller, then, bind the viewcontroller code file to be bound to custom. Press ctrl and drag the Navigation Controller to the newly created View Controller. In the displayed dialog box, set it to root view controller.


You can set the title of this view controller, for example.




Create a New View Controller and bind a. m file in the same step. Drag a button to the first View Controller, press ctrl, and drag the second View Controller. In the displayed dialog box, select show to click the button to jump to the second View Controller.



Advantage: All xib instances are stored in a storyboard file, which is easy to manage and can be easily redirected to View Controller, greatly reducing the amount of code.
Disadvantages: because all xib files are concentrated in one file, it is difficult to divide the work of some large projects, in addition, the storyboard method consumes more system resources than the code and xib method.


V. Summary

Personally, I prefer xib as the main way to build views, and code creation as an aid, because I switched from Android development to ios development, I am used to the method that corresponds to an xml layout file for each activity. xib can also meet my needs. Currently, it is used in this way. For project requirements, I am using storyboard, after all, this is the future development trend.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.