Starting from scratch, I learned iOS development (17th): storyboards (I)

Source: Internet
Author: User
Tags exit in

Before starting this chapter, Let's explain how to update xcode to the latest version 4.6.1 (4h512:

You can open the app store on your computer and search for xcode. The first one that appears is xcode. Then you can click Install directly, which is convenient and intelligent, if your computer has an old version of xcode, it will prompt you to delete it. It is easy for me to press it down.

In addition, the tutorials I have used have been upgraded from the beginning.

This is easy to find.

Well, there is nothing different from the others. Next we will start learning this article.

1) storyboard Introduction
This course introduced a new things when I was in iOS 5: storyboard, which is simply translated into a "Story version" (well, I think this name is quite frustrating ), it simplifies some steps for app development, such as automatically adding the necessary Delegate/datasource for us, switching between multiple views, and connecting each view using graphs and lines, this allows us to clearly see the relationship between views. The advantage is that it reduces the workload we need to switch over the view before managing the view, so that we can focus more on the implementation of specific functions, then we have a general understanding of the relationship between the entire app view.

The storyboard is based on the XIB (xcode's interface builder), but a storyboard can contain multiple XIB, each of which is bound to its own controller. It seems that the following is a simple example to intuitively understand what a storyboard is.

2) create a simple storyboard
Create a project, select Application on the left, select single view application on the right, and click Next

Name the project "simple storyboard", select use storyboards, and click Next

Find a place to save the new project and complete the creation.

In project navigator, many of the files created by default are the same as before, including bidappdelegate and bidviewcontroller. However, we did not find the XIB file and replaced it with a mainstoryboard. storyboard. In this storyboard, the system hides the XIB created by default and selects mainstoryboard. storyboard, an XIB will appear in the editor area, and the Controller file of the entire XIB is bidviewcontroller. So far, all the files created by default are matched.

Open the dock, select the view controller node, and expand it. You will find that the icons displayed in a black area under layout area are the same as those in the dock, the black area and the view above constitute a scenario called scene. (There is another exit in scene, which is not introduced, because it is omitted in the book) there is a big arrow on the left of the view, this arrow is used to indicate the start view of the app.

There is a small icon in the lower right of layout area, which is used to switch between iPhone 4 and iPhone 5 (in our example, it is based on the iPhone 4 interface)
 

Let's continue with this example. Drag a label from the object library to the center of the view, double-click the label, and enter "simple"

Compile and run your program. The simplest storyboard app is complete.

When we use storyboard to develop an app, many programs will help us, including how to load the default XIB. If you select the project name in project navigator

In Editing pane, you can find the storyboard loaded by the program by default. In this example, the default storyboard is mainstoryboard. storyboard.

3) storyboard with uitableviewcontroller
In the previous examples, we have used uitableviewcontroller many times. We should be familiar with the operation method. Generally, tableview contains many cells, each cell has an identifier. The method used to create a cell is cellforrowatindexpath. This will still be used in storyboard, but it will be relatively simple. Next we will continue with the above example.

Select the simple storyboard folder in project navigator, right-click, and select "new file... ", in the pop-up window, select cocoa touch on the left, select objective-C class on the right, click Next, and name the class bidtasklistcontroller and subclass of uitableviewcontroller in the next window, click Next to complete the creation.

Select mainstoryboard. storyboard and drag a table View Controller to layout area from the object library.

In the dock, select the table View Controller you just dragged in (this will hold the entire table View Controller in layout area)

Enable identity inspector and set the class to bidtasklistcontroller. After the settings are complete, the table view in the dock is changed to the task list controller.

In this way, the newly added tableviewcontroller corresponds to its class, And tableview also knows where it can obtain the data it needs.

On the dragged table View Controller, there is a default cell (prototype cells). We can add identifier for it and customize its own cell style on it (note, we can add any number of prototype cells, each cell is differentiated by identifier, and different styles are customized. The cell here is just a prototype, and a formal cell is generated based on the prototype cell, an example is provided later ). Select the entire default cell, open attributes inspector, find identifier, and enter plaincell

Then drag a label from the object library to the prototype cell. The label layout depends on your hobbies. Select the label, locate the tag in attributes inspector, and set its value to 1, in this way, you can find the label through the tag value in the code.

Next, select the entire cell. You can also select it in the dock. This is more accurate. Then, press command + D, or select Edit> duplicate from the menu bar to copy a cell, in this way, there are two prototype cells in Table view.

(Here is a very useful tips. When you want to directly select the desired element in the view, but it is difficult to directly select too many elements superimposed on a view, at this time, you hold down the shift and control keys on the keyboard at the same time, and then click the mouse on the element you want to select, a window will pop up, the above lists all the elements that exist under the place where the mouse clicks, and then you can proceed with the selection to make the changes very simple.
For example, if you click label in cell

There are 4 stacked elements in the cursor position.

If we click the mouse on the cell

The label is missing. There are only three elements.

In this case, it is very easy to use this method to select elements. I still admire Apple's consideration and design in terms of details .)

Select the newly added cell and assign the Identifier value to attentioncell in attributes inspector.

Select the label and set its color to red in attributes inspector.

Now, all the operations on this table view are completed. Before you start writing code, you can move the big arrow in layout area to this table view, in this way, the view is displayed by default when the program is loaded.

Save mainstoryboard. storyboard and start the encoding below.

Open the bidtasklistcontroller. M file and you will find that many common methods already exist:
Viewdidload
Didreceivememorywarning
Numberofsectionsintableview
Numberofrowsinsection
Cellforrowatindexpath
Didselectrowatindexpath
You only need to fill in the Code directly in these methods. Add the following code:

#import "BIDTaskListController.h"@interface BIDTaskListController ()@property (strong, nonatomic) NSArray *tasks;@end@implementation BIDTaskListController......- (void)viewDidLoad{    [super viewDidLoad];    // Uncomment the following line to preserve selection between presentations.    // self.clearsSelectionOnViewWillAppear = NO;     // Uncomment the following line to display an Edit button in the navigation bar for this view controller.    // self.navigationItem.rightBarButtonItem = self.editButtonItem;        self.tasks = @[@"Walk the dog",                   @"URGENT: Buy milk",                   @"Clean hidden lair",                   @"Invent miniature dolphins",                   @"Find new henchmen",                   @"Get revenge on do-gooder heroes",                   @"URGENT: Fold laundry",                   @"Hold entire world hostage",                   @"Manicure"];}......#pragma mark - Table view data source- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{#warning Potentially incomplete method implementation.    // Return the number of sections.    return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{#warning Incomplete method implementation.    // Return the number of rows in the section.    return [self.tasks count];}

First, define an nsarray-type tasks to save the rows in Table view and assign values to tasks in viewdidload. (The syntax here is a little different from the assignment method I have seen before, the more SQL statements are written, the more refined the statement is.) In numberofsectionsintableview, 1 is returned, indicating that there is only one section. In numberofrowsinsection, the number of rows in the section is returned. These are all very simple, and then add the code

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *CellIdentifier = @"Cell";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];        NSString *identifier = nil;    NSString *task = [self.tasks objectAtIndex:indexPath.row];    NSRange urgentRange = [task rangeOfString:@"URGENT"];    if (urgentRange.location == NSNotFound) {        identifier = @"plainCell";    } else {        identifier = @"attentionCell";    }    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];        // Configure the cell...        UILabel *cellLabel = (UILabel *)[cell viewWithTag:1];    NSMutableAttributedString *richTask = [[NSMutableAttributedString alloc] initWithString:task];    NSDictionary *urgentAttributes = @{NSFontAttributeName : [UIFont fontWithName:@"Courier" size:24],                                       NSStrokeWidthAttributeName : @3.0};    [richTask setAttributes:urgentAttributes range:urgentRange];    cellLabel.attributedText = richTask;        return cell;}

The Code defines an identifier at the beginning, and then obtains the task in tasks according to indexpath. The nsange can be considered as a range or an arrangement, which can be searched by this range or arrangement to another object, if yes, the start position is returned. If no result is found, the nsnotfound is returned. The urgentrange object of nsange defines a field "urgent", which matches in the task. If yes, the cell assigns plaincell to identifier, if not, assign the attentioncell to the identifier. Then, based on the identifier, obtain the corresponding cell from the tableview method dequeuereusablecellwithidentifier.

The next section is to operate the label on the cell. Remember that we set the label to 1 in attributes inspector just now? Here we use viewwithtag to locate the label in the cell and assign values to the label. Then, some operations are performed on the specific string "urgent, change its font properties. After all, our attention is not focused on this. After the label operation is complete, it is assigned to the celllabel and the cell is returned.

Well, compile and run (there will be warning during compilation, so ignore this and the compilation will still be successful. These warning tells you that XIB in storyboard is not used, the arrow does not point to it and is not related to the current view. Therefore, it is normal to operate it without warning. The effect is as follows:

If the task contains the string "urgent", the cell with Identifier being attentioncell will be used; otherwise, the cell with Identifier being plaincell will be used.

4) Static Cells
In most cases, cells in Table view need to be dynamically generated. During app running, different numbers or styles of cells are generated according to different source values. However, in some cases, we can know in advance what the cell to be generated looks like, and it is fixed. We call such a cell static cells, which corresponds to a dynamic cell. Here we will give a simple example to illustrate this situation.

We do not need to create a new project, but add Code directly in the above program. Select the simple storyboard folder in project navigator, right-click, and select "new file... ", in the pop-up window, select cocoa touch on the left, select objective-C class on the right, click Next, and name the class bidstaticcellscontroller and subclass of uitableviewcontroller in the next window, click Next to complete the creation.

Select mainstoryboard. storyboard, drag a table View Controller from the object library to layout area, place it on the right of the original two views, and then point the arrow to the newly added view.

The rightmost view in the figure is the newly added view, which looks relatively small because I have located in the lower right corner of layout area, so that I can conveniently observe each view (of course, in a reduced state, there is no way to operate the view. You can only move its position. To operate the view, you must enlarge the view back to its normal size)

Select the table view in the controller you just added, open attributes inspector, find the content, select "static cells" in the drop-down box, locate the style, and select "grouped" in the drop-down box"

The style of the table view also changes. When three rows appear, the style of the section changes to a rounded rectangle.

Select the section and set its attributes inspector as follows. Change rows to 2 and enter "silliest clock ever" in the header"

 

Section after modification

Next, set the two cells, select the first cell, and set its style to "Left detail" in attributes inspector"

Double-click the title and change it to "the date". Repeat the above steps and change the title of the second cell to "the time ".

Then, we will create two outlet objects pointing to two detail objects respectively, so that after the app runs, their values can be changed.

Now, associate the table View Controller with its class, select table View Controller in the dock, open identity inspector, and enter "bdistaticcellscontroller" in the class. The name in the dock also changes.

Select the controller in the dock, and set the editor mode to assistant editor, so that bidstaticcellscontroller. the H file will be opened (if this file is not opened, open it manually), select the detail in the first cell, and control-drag to bidstaticcellscontroller. H and release, a window will pop up, name "datelabel"

Perform the same operation on the detail in the second cell, name the name as "timelabel", and then add the bidstaticcellscontroller. h

#import <UIKit/UIKit.h>@interface BIDStaticCellsController : UITableViewController
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;@property (weak, nonatomic) IBOutlet UILabel *timeLabel;@end

Write the following code, open bidstaticcellscontroller. m, and delete the following three methods:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{#warning Potentially incomplete method implementation.    // Return the number of sections.    return 0;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{#warning Incomplete method implementation.    // Return the number of rows in the section.    return 0;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *CellIdentifier = @"Cell";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];        // Configure the cell...        return cell;}

Because we use static cells, the number of sections in Table view and the number of cells in the Section are fixed, and we do not need to create two cells in total, it is always displayed on the screen.

Add the following code

- (void)viewDidLoad{    [super viewDidLoad];    // Uncomment the following line to preserve selection between presentations.    // self.clearsSelectionOnViewWillAppear = NO;     // Uncomment the following line to display an Edit button in the navigation bar for this view controller.    // self.navigationItem.rightBarButtonItem = self.editButtonItem;        NSDate *now = [NSDate date];    self.dateLabel.text = [NSDateFormatter                           localizedStringFromDate:now                           dateStyle:NSDateFormatterLongStyle                           timeStyle:NSDateFormatterNoStyle];        self.timeLabel.text = [NSDateFormatter                           localizedStringFromDate:now                           dateStyle:NSDateFormatterNoStyle                           timeStyle:NSDateFormatterLongStyle];}

In viewdidload, datelabel and timelabel are set respectively. For nsdate and nsdateformatter instructions, let's Google them. I will not explain them in detail here.

Compile and run the program. The effect is as follows:

 

Simple storyboard

 

 

 

 

 

 

 

 

 

Related Article

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.