Objective-c--ui Advanced Development First day (Uipickerview and Uidatepicker)

Source: Internet
Author: User

First, the Knowledge point

1. Introduction to Data selection controls Uipickerview and date selection controls Uidatepicker controls

* Case of Uipickerview

* Ordering System

* City Selection

* Flag Selection

* Case of Uidatepicker

* Introduction and basic use of Uitoolbar

* Introduction and presentation of Uibarbuttonitem

* Set date or time data to a text box

2. Introduction of project configuration file

* Apply Avatar

* Apply settings for loading pictures

* Info.plist File Description:

* Common key

* Xcode 6 was previously named after "project name-info.plist" and Xcode 6 was only info.plist

Now the historical version of Xcode's URL

https://developer.apple.com/downloads/

* View full key in Info.plist with open as source code

* Use code to get information from Info.plist

* PCH File description

* Create PCH File

* Configure basic information

* Print Macro Demo

Second, the use of Uipickerview

    • Role:
      • Select data from the specified data source
      • Typically, a Uitextfield "Inputview" appears when a text box is selected, and the control appears in the keyboard that pops up.
    • Attention:
      • You need to specify the data source object and the proxy object before using Pickerview
      • Two protocols that need to be used
        • Uipickerviewdatasource Data Source Protocol
        • Uipickerviewdelegate Proxy Protocol

1. Data source method

Set column:

Numberofcomponentsinpickerview: (Uipickerview *) Pickerview

Set Line:

Pickerview: (Uipickerview *) Pickerview numberofrowsincomponent: (Nsinteger) component

2, delegate Agent method

Setting display content (Titleforrow)

-(NSString *) Pickerview: (Uipickerview *) Pickerview Titleforrow: (nsinteger) Row forcomponent: (Nsinteger) component

You can also set the display view (Viewforrow)

-(UIView *) Pickerview: (Uipickerview *) Pickerview Viewforrow: (nsinteger) Row forcomponent: (Nsinteger) component Reusingview: (UIView *) view

Gets the data method selected by Pickerview: (Didselectrow)

-(void) Pickerview: (Uipickerview *) Pickerview Didselectrow: (nsinteger) Row incomponent: (Nsinteger) component

Three, random number generation (Arc4random_uniform)

Arc4random (): C language function, randomly generates an unsigned integer (0-2 of 32 times)

Arc4random ()% (n+1) randomly generates a number between 0-n

Arc4random_uniform (256) recommended by Apple, randomly generate a number between 0-n

(Randomly generated colors:

[Uicolor colorwithred:arc4random_uniform (/255.0 green:arc4random_uniform)/255.0 Blue:arc4random_uniform ( /255.0 alpha:1.0];

One problem: Randomly generated numbers may match the number of current selections, causing Pickerview to change:

Solve:

1. Get the current selection:

Gets the currently selected line number, or regenerates the random number if it is the same as the random number

Nsinteger Selrow = [Self.pickerview selectedrowincomponent:i];

2, and random number to compare, if consistent, then regenerate random number

Regenerate random numbers if they are not the same

Randomnum =arc4random_uniform ((int) count);

3, if not consistent, the display of random numbers between

[_pickerview selectrow:randomnum incomponent:i animated:true];

Iv. City Selection (the selection of the No. 0 column will affect the data display in column 1th)

1, Focus: How to display the line:

Judging, if it is the No. 0 column: Each row shows the province name:

if (component= =0)

{

Province =self.dataarray[row];

return province.name;

}

Judging if it's not the No. 0 column:

A, gets the array subscript for the selected province (subscript in the No. 0 column)

Nsinteger selproidx =[pickerview selectedrowincomponent:0];

B. Access to selected provinces

Privince =self.dataarray[selproidx]

C. Get an array of cities included in the selected province

Nsarray *citiesattay =province.cities;

D. Load the city name and display

return Citiesattay[row];

2, Focus: Found a problem: the City this column of data, before scrolling, will not automatically update, need to manually refresh

Update and display data in Didselectrow and select columns to refresh using reloadcomponent

/If scrolling is the No. 0 column, refresh the first column of city data

if (component==0)

{

[Pickerview reloadcomponent:1];

Select the No. 0 row of the first column

[Pickerview selectrow:0 incomponent:1 Animated:yes];

}

3, Uipickerview important bug: Array out of bounds causes the program to crash

/**

Crash reasons:

1th time selected province, display city data fixed

When scrolling again, if not stopped, the city's data is still the original

However, when the city's data is refreshed, the original city array is inconsistent with the current city data to be displayed, causing the array to break out of bounds

Solve:

When calculating how many rows are displayed, save the saved model and display it later in the saved province to get the data display

*/

In

Numberofrowsincomponent: Solution:

2. Find the provincial model according to subscript

Czprovince *province =self.dataarray[selproidx];

Save the last displayed number of rows

Self.selpro =province;

return self.selPro.cities.count;

After this, the call to cities is selected directly through:

return Self.selpro.cities[row];

method to directly display the Access data

V. Country selection (the case of custom view is shown in Uipickerview)

1. Create a view from Xib

2. Return view/Row height by Flagview method

+ (Instancetype) Flagview

{

return [[[NSBundle Mainbundle] loadnibnamed:@ "Czflagview" Owner:nil Options:nil] lastobject];

}

Who decides who is going to manage the line height

+ (CGFloat) rowHeight

{

return 80;

}

3. Get view or row height (in-(UIView *) Pickerview: (Uipickerview *) Pickerview Viewforrow: (nsinteger) Row forcomponent: (Nsinteger) Component Reusingview: (UIView *) in the View method: As well as in the Rowheightforcomponent method

Czflagview *flagview =[czflagview Flagview];

#pragma mark-how variable the row height according to xib in the view to define a method, directly tell the row high, and in-house implementation

-(CGFloat) Pickerview: (Uipickerview *) Pickerview rowheightforcomponent: (Nsinteger) component

{

return [Czflagview RowHeight];

}

Vi. Uidatepicker Date Acquisition

0, Introduction: Uidatepicker (and implementation)

Alarm clock..

Format fixed, data is regular, ensure the date format is correct

Usually appear in the form of Uitextfield Inputview (usually not put a uidatepicker alone)

Click the text box no longer pops up is the system keyboard, but a time selector (there is a function bar at the top)

Use:

1), Initialize

2), common settings

Mode:4: Displays only time, date, time, and date counter and timer timers similar to

Locale: Localization

TextField has a Inputview attribute

Self.textField.inputView =[[uidatepicker Alloc]init];

Inputaccessoryview setting the toolbar above the keyboard

1. Date of acquisition

NSDate *date =[_pickerview Date];

2. Date to string and display date

3. Use of TextField Inputview and Inputaccessoryview attributes

#pragma mark-Considering that creating uipickerview directly in the Inputview attribute means that each click of TextField will be recreated: lazy loading with controls

The Inputview property of TextField

Self.textField.inputView =self.pickerview;

Set the toolbar on the upper part of the keyboard

Self.textField.inputAccessoryView =self.toolbar;

4. Lazy Loading of controls

A, @property (Nonatomic,strong) Uitoolbar *toolbar;

Note Use the strong strong quote: Why?

Strong: Will not be released

Why do you use weak when writing controls?

Because dragging in the storyview means adding the control to the controller, the controller's view has a strong pointer to the control, so at this point, if the control is also strongly pointing to the controller, it is not impossible to release, but it needs to be freed two times.

So why use weak when creating a code: Because when the control is created, it is then added to the view of the controller, and the controller has a strong reference to the control.

B

-(Uidatepicker *) Pickerview

{

if (_pickerview ==nil)

{

1. Initialization

_pickerview =[[uidatepicker Alloc]init];

2. Localization

_pickerview.locale =[nslocale localewithlocaleidentifier:@ "fr"];

3. Display mode of date selector

_pickerview.datepickermode =uidatepickermodedate;

}

return _pickerview;

}

C, call Self.pickerview directly to get

5. Introduction to New control toolbar and 3 ways to create a button

Mode one, general creation (Initwithtitle)

Uibarbuttonitem *cancle =[[uibarbuttonitem alloc]initwithtitle:@ "Cancel" Style:uibarbuttonitemstyleplain target:self Action: @selector (Cancleclick)];

Mode two, System fiexiblespacing button (Initwithbarbuttonsystemitem)

Create Fiexiblespacing System button

Uibarbuttonitem *fiexiblespacing =[[uibarbuttonitem Alloc]initwithbarbuttonsystemitem: Uibarbuttonsystemitemflexiblespace target:self Action:nil];

Mode three, using button form outsourcing Itembutton buttons (initwithcustomview)

UIButton *donebtn =[[uibutton alloc]initwithframe:cgrectmake (200, 0, 40, 40)];

[Donebtn settitle:@ "OK" forstate:uicontrolstatenormal];

[Donebtn Settintcolor:[uicolor Blackcolor];

[Donebtn Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];

[Donebtn addtarget:self Action: @selector (Doneclick) forcontrolevents:uicontroleventtouchupinside];

Uibarbuttonitem *done = [[Uibarbuttonitem alloc]initwithcustomview:donebtn];

6, keyboard disappears two kinds of settings

Keyboard disappears:

1, Self.textfield Resignfirstsresponse

2, Self.view Endediting:yes]; (for multiple need to set the keyboard to disappear)

7, toolbar some points of attention

V. Click Cancel or complete the action you want to perform

Uitoolbar background settings: Bar Tint settings background is not visible

Item's picture and text cannot be set at the same time

To display both text and pictures, you need to add a button

But the color is not the same as item

Way one, Assets-image-Render as

Mode two, code modification (imagewithrenderingmode:uiimagerenderingmodealwaysoriginal)

For example:

Create a button with a picture item

UIImage *img=[uiimage imagenamed:];

Uibarbuttonitem *done =[uibarbutton Item alloc]initwithimage:img

Will find that an orange image turns into a system color.

IMG Imagewithrenderingmode:uiimagerenderingmodealwaysoriginal];

VII. Introduction of project documents

Introduction to project Documents

Review: Uipickerview/uidatepicker

1, Info.plist

2. pch file (disappears after Xcode6 because the compilation is too slow)

0) Empty projects can be established through New-target-file

Previous folder: Frequently used files are displayed

1) Assets.scassets-app icon: app Avatar

Launch screen-start picture

2) infoplist file

Xcode6 Previously, the name is "project name-info.plist"

XML language

Application Transport Security Nsallowsarbitraryloads

2.1) Bundle identifier: The only indication of the application: If two applications are used, the same label will be overwritten (

Application upgrade is also by judging if two bundleid consistent, then directly overwrite the original program

2.2) Bundle (display name)

App Name

2.3) Bundle version

Version number of the application (internally used version number)

Bundle Visions String Short: The version number after the application is published

2.4) Mainstoryboard file base Name:main

Corresponds to Main.storyboard: Why did you open Mainstoryboadr after startup?

2.5) Supported Interface orientations

The home button direction of the phone

2.6) Gets the version number: The description of which features are currently updated by the application when they are updated:

Nsdictionary *infodict=[nsbundle mainbundle].infodictionary; (Can get to info.plist file read-only, can print to see)

Iii. pch File

1. Create: other-pct Fileprefixheader: Precompiled

2. Function:

A, help us to put together all the common macros

[Uicolor colorwithred:arct4random_uniform (/255.0 green:arc4random_uniform)/255.0 Blue:arc4random_uniform ( /255.0 alpha:1.0)];

Define the color directly in the prefixheader.pch file, define the macro: # define Czrandom

When defining a macro, try to add the prefix of the project

B, Configuration

Project-Targets-build Settings-prefix header-debug (Beta)/release (at the time of release)

Before each release, consider whether the prefix header file is correct (convenient way: Click on the right side to see the path to the prefixheader.pch file "./" point to the project Files directory expansion will find that the test and release are the same PCH file)

C, can control the printing

#ifdef DEBUG

# define Czlog (... ) NSLog (__va_args__)

#else

Release version

#define CZLOG (...)

#denif

Write NSLog into Czlog.

If the release version prohibits printing

Item-targets-editsheme-run-info-bulid Configuration-release

D. Save the common header file

If the header file of a tool class is used in this class and other classes, it is possible to include the solution for that header file every time: Avoid multiple imports

In the PCH file: #import "CZTool.h"

E, C language-type files

Contains C language files, compile the time will be error, because there is no OC in C language such as header files

Need to block OC-written content in PCH files

#ifdef __objc__

#endif

Objective-c--ui Advanced Development First day (Uipickerview and Uidatepicker)

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.