The use instance of Uipickerview selection bar control in IOS app _ios

Source: Internet
Author: User
Tags uikit

The Uipickerview control is a more common picker control than the Uidatepicker control, which can be understood as a specially made date-selected control that is processed from the Uipickerview control.
The use of Uipickerview controls is a bit more complex than uidatepicker. The small example in this article will use the Uipickerview control to make two kinds of effect, the first one has only one turntable, the second has two turntable, but these two turntable have no dependence, namely change one of the turntable's choice, does not have the influence to the second turntable. The next article will be an example of a dependency between the turntable.
The diagram below is our effect chart:

The first Uipickerview control can be used to select Horse,sheep,pig,dog,cat,chicken,duck,goose; the second Uipickerview adds a turntable on the first basis.
Gossip less, then start.
1, run Xcode, create a new single View application, the name is Uipickerview Test1, and other settings as shown below:

2, click Viewcontroller.xib, and then drag a picker view control to the view:

Then drag a button below the picker view and modify the name to select:

3. Create a outlet mapping for the picker View control in ViewController.h, with the name Mypickerview, and then create an action map for the Select button, with the name buttonpressed, the specific method is not stated, You can refer to the previous article.
4, select the Picker view control, open the Connections Inspector, find delegate and DataSource, pull the string from the right circle to the file's Owner:

5, click ViewController.h, add code in it:

Copy Code code as follows:

#import <UIKit/UIKit.h>

@interface Viewcontroller:uiviewcontroller<uipickerviewdelegate, uipickerviewdatasource>

@property (Weak, nonatomic) Iboutlet Uipickerview *mypickerview;
@property (Strong, nonatomic) Nsarray *mypickerdata;

-(Ibaction) buttonpressed: (ID) sender;

@end


Note that you add the angle brackets and the contents behind the @interface, and we will viewcontroller as the delegate and DataSource of Picker view.

6, Code add:

6.1 Click VIEWCONTROLLER.M to add the code to the next line in @implementation:

Copy Code code as follows:

@synthesize Mypickerdata;

6.2 Find the Buttonpressed method, add the following code:
Copy Code code as follows:

-(Ibaction) buttonpressed: (ID) Sender {
Nsinteger row = [Mypickerview selectedrowincomponent:0];
NSString *selected = [Mypickerdata objectatindex:row];
NSString *msg = [[NSString alloc] Initwithformat:
@ "You selected%@!", selected];
Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "hello!"
Message:msg
Delegate:nil
cancelbuttontitle:@ "Yes, I Did."
Otherbuttontitles:nil];
[Alert show];
}

6.3 Find the Viewdidload method in which to add code:
Copy Code code as follows:

-(void) viewdidload
{
[Super Viewdidload];
Do no additional setup after loading the view, typically from a nib.
Nsarray *array = [[Nsarray alloc] initwithobjects:@ "horse", @ "Sheep", @ "Pig", @ "Dog", @ "Cat", @ "chicken", @ "Duck", @ "Goose" ", nil];
Self.mypickerdata = array;
}

6.4 Find the Viewdidunload method in which to add code:
Copy Code code as follows:

-(void) viewdidunload
{
[Self setmypickerview:nil];
[Super Viewdidunload];
Release any retained subviews of the main view.
e.g. Self.myoutlet = nil;
Self.mypickerview = nil;
Self.mypickerdata = nil;
}

6.5 Add code before @end:
Copy Code code as follows:

#pragma mark-
#pragma mark Picker Data Source Methods

-(Nsinteger) Numberofcomponentsinpickerview: (Uipickerview *) Pickerview {
return 1;
}

-(Nsinteger) Pickerview: (Uipickerview *) Pickerview numberofrowsincomponent: (Nsinteger) Component {
return [Mypickerdata Count];
}

#pragma mark Picker Delegate Methods
-(NSString *) Pickerview: (Uipickerview *) Pickerview Titleforrow: (nsinteger) Row forcomponent: (Nsinteger) Compone NT {
return [Mypickerdata Objectatindex:row];
}


7. Operation:

The above example has only one turntable, next we add a turntable on this basis, the first turntable is unchanged, the second turntable can choose Tree,flower,grass,fence,house,table,chair,book,swing. Just add the code.

8, click ViewController.h, add code to the next line in @interface:

Copy Code code as follows:

@property (Strong, nonatomic) Nsarray *mypickerdata_2;

9, click VIEWCONTROLLER.M, add code in it:

9.1 Add code to the next line in @implementation:

Copy Code code as follows:

@synthesize mypickerdata_2;

9.2 Find the Viewdidload method in which to add code:
Copy Code code as follows:

-(void) viewdidload
{
[Super Viewdidload];
Do no additional setup after loading the view, typically from a nib.
Nsarray *array = [[Nsarray alloc] initwithobjects:@ "horse", @ "Sheep", @ "Pig", @ "Dog", @ "Cat", @ "chicken", @ "Duck", @ "Goose" ", nil];
Self.mypickerdata = array;
Nsarray *array_2 = [[Nsarray alloc] initwithobjects:@ ' tree ', @ "Flower", @ "Grass", @ "Fence", @ "house", @ "Table", @ "Chair", @ "book", @ "Swing", nil];
self.mypickerdata_2 = array_2;
}

9.3 Find the Viewdidunload method in which to append the code:
Copy Code code as follows:

-(void) viewdidunload
{
[Self setmypickerview:nil];
[Super Viewdidunload];
Release any retained subviews of the main view.
e.g. Self.myoutlet = nil;
Self.mypickerview = nil;
Self.mypickerdata = nil;
self.mypickerdata_2 = nil;
}

9.4 Find the Buttonpressed method, modify the code:
Copy Code code as follows:

-(Ibaction) buttonpressed: (ID) Sender {
Nsinteger row = [Mypickerview selectedrowincomponent:0];
Nsinteger row_2 = [Mypickerview selectedrowincomponent:1];

NSString *selected = [Mypickerdata objectatindex:row];
NSString *selected_2 = [mypickerdata_2 objectatindex:row_2];

NSString *msg = [[NSString alloc] Initwithformat:
@ "You selected%@ and%@!", selected, Selected_2];
Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "hello!"
Message:msg
Delegate:nil
cancelbuttontitle:@ "Yes, I Did."
Otherbuttontitles:nil];
[Alert show];
}


9.5 Find the Numberofcomponentsinpickerview method and modify its return value to 2:
Copy Code code as follows:

-(Nsinteger) Numberofcomponentsinpickerview: (Uipickerview *) Pickerview {
return 2;
}

9.6 Find the Numberofrowsincomponent method, modify the code:
Copy Code code as follows:

-(Nsinteger) Pickerview: (Uipickerview *) Pickerview numberofrowsincomponent: (Nsinteger) Component {
if (component = = 0) {
return [Mypickerdata Count];
}
return [mypickerdata_2 Count];
}

9.7 Find the following method to modify the code:
Copy Code code as follows:

-(NSString *) Pickerview: (Uipickerview *) Pickerview Titleforrow: (nsinteger) Row forcomponent: (Nsinteger) Component {
if (component = = 0) {
return [Mypickerdata Objectatindex:row];
}
return [mypickerdata_2 Objectatindex:row];
}

10. Operation:

Advanced instance
The following is done with the Uipickerview control: it has two turntable (Component), when the left side of the turntable changes the selection value, the right turntable all the options are changed. As shown in the following illustration:

To achieve this effect, first create two Nsarray objects, one for each turntable. Then create a Nsdictionary object. We can imagine that the data is a tree, nsdictionary can be considered as a table with two columns, the first column is a keyword, and each keyword corresponds to a Nsarray object that stores a series of NSString objects in the Nsarray array.

In this example, the first example stores some provinces, and the second column stores provincial-level cities.

In fact, the way to achieve the same as the previous article, the only difference is to achieve: change the left side of the turntable options, the right turntable content changes. The function to use the functions we used last time.

This time, we first write the code to use, and then use Interface Builder to create the control, implementation mapping, and so on.

1, run Xcode 4.2, create a new single View application, the name is Uipickerview Test2:

2, create the data. The data we use are as follows:

In the previous article has mentioned the plist file, now, we will use the Plist file to store the above data. To do this, select File-new-new File, in the open window, select the resource in iOS on the left, and select Property List on the right:

Click Next, in the open window, enter the name in Save as Provincecities,group select supporting Files:

When you click Create, you create the provincecities.plist. Then add the data to it, as shown in the following illustration:

3, click ViewController.h, add code to it:

Copy Code code as follows:

#import <UIKit/UIKit.h>

#define Kprovincecomponent 0
#define Kcitycomponent 1

@interface Viewcontroller:uiviewcontroller <uipickerviewdelegate, uipickerviewdatasource>

@property (Strong, nonatomic) Iboutlet Uipickerview *picker;
@property (Strong, nonatomic) Nsdictionary *provincecities;
@property (Strong, nonatomic) Nsarray *provinces;
@property (Strong, nonatomic) Nsarray *cities;

-(ibaction) buttonpressed;

@end


4, click VIEWCONTROLLER.M, add code to it:

4.1 Add code to the next line in @implementation:

Copy Code code as follows:

@synthesize Picker;
@synthesize provincecities;
@synthesize provinces;
@synthesize cities;

4.2 Adding code to the Viewdidload method:
Copy Code code as follows:

-(void) viewdidload
{
[Super Viewdidload];
Do no additional setup after loading the view, typically from a nib.
NSBundle *bundle = [NSBundle mainbundle];
Nsurl *plisturl = [Bundle urlforresource:@ "Provincecities" withextension:@ "plist"];

Nsdictionary *dictionary = [Nsdictionary Dictionarywithcontentsofurl:plisturl];
Self.provincecities = dictionary;
Nsarray *components = [Self.provincecities AllKeys];
Nsarray *sorted = [Components sortedarrayusingselector: @selector (compare:)];
Self.provinces = sorted;

NSString *selectedstate = [Self.provinces objectatindex:0];
Nsarray *array = [Provincecities objectforkey:selectedstate];
self.cities = array;
}

In code
Copy Code code as follows:

NSBundle *bundle = [NSBundle mainbundle];

Used to get the main Bundle of the current program, this Bundle can be viewed as a folder in which the content follows a specific framework. One of the main uses of the main bundle is to use the resources in the program, such as pictures, sounds, and so on, in this case the plist file is used. The following line
Copy Code code as follows:

Nsurl *plisturl = [Bundle urlforresource:@ "Provincecities" withextension:@ "plist"];

To get the path to the provincecities.plist, and then place the contents of the file in a Nsdictionary object, using the
Copy Code code as follows:

Nsdictionary *dictionary = [Nsdictionary Dictionarywithcontentsofurl:plisturl];

4.3 Find the Viewdidunload method, add code:
Copy Code code as follows:

-(void) viewdidunload
{
[Super Viewdidunload];
Release any retained subviews of the main view.
e.g. Self.myoutlet = nil;
Self.picker = nil;
Self.provincecities = nil;
Self.provinces = nil;
Self.cities = nil;
}

4.4 Add code before @end to implement the Buttonpressed method:
Copy Code code as follows:

-(Ibaction) buttonpressed: (ID) Sender {
Nsinteger Provincerow = [Picker selectedrowincomponent:kprovincecomponent];
Nsinteger Cityrow = [Picker selectedrowincomponent:kcitycomponent];

NSString *province = [Self.provinces objectatindex:provincerow];
NSString *city = [Self.cities objectatindex:cityrow];

NSString *title = [[NSString alloc] initwithformat:@ "you chose%@.", City];
NSString *message = [[NSString alloc] initwithformat:@ "%@ belong to%@", City, province];

Uialertview *alert = [[Uialertview alloc] initwithtitle:title message:message delegate:nil cancelbuttontitle:@ "OK" Otherbuttontitles:nil];
[Alert show];
}

4.5 Add code before @end:
Copy Code code as follows:

#pragma mark-
#pragma mark Picker Date Source Methods
-(Nsinteger) Numberofcomponentsinpickerview: (Uipickerview *) Pickerview {
return 2;
}

-(Nsinteger) Pickerview: (Uipickerview *) Pickerview numberofrowsincomponent: (Nsinteger) Component {
if (component = = Kprovincecomponent) {
return [self.provinces Count];
}
return [self.cities Count];
}

#pragma mark Picker Delegate Methods
-(NSString *) Pickerview: (Uipickerview *) Pickerview Titleforrow: (Nsinteger) Row forcomponent: (Nsinteger) component {
    if (component = = kprovincecomponent) {
  & nbsp;     return [self.provinces Objectatindex:row];
   }
    return [self.cities Objectatindex:row];
}

-(void) Pickerview: (Uipickerview *) Pickerview Didselectrow: (nsinteger) Row incomponent: (Nsinteger) Component {
if (component = = Kprovincecomponent) {
NSString *selectedstate = [Self.provinces objectatindex:row];
Nsarray *array = [Provincecities objectforkey:selectedstate];
self.cities = array;
[Picker selectrow:0 incomponent:kcitycomponent Animated:yes];
[Picker reloadcomponent:kcitycomponent];
}
}

-(CGFloat) Pickerview: (Uipickerview *) Pickerview widthforcomponent: (Nsinteger) Component {
if (component = = Kcitycomponent) {
return 150;
}
return 140;
}


As you can see, most of the code is the same as compared to the example in the previous article, with the addition of Pickerview: (Uipickerview *) Pickerview Didselectrow: (nsinteger) row incomponent: ( Nsinteger) component This method. In this method, when the value of the left turntable is detected, the contents of the self.cities are replaced with the corresponding array, and the [picker reloadcomponent:kcitycomponent] is executed;

One last method

Copy Code code as follows:

(cgfloat) Pickerview: (Uipickerview *) Pickerview widthforcomponent: (Nsinteger) component

Can be used to modify the width of each turntable, although in this case is not necessary, but we have to know how to do.

The end of the Code section is followed by the use of Interface Builder to add controls and create mappings.

5, click Viewcontroller.xib, to add a Uipickerview control and a button, the name of the buttons changed to "Select", specific methods to refer to the previous

The next thing to do is to pull a few lines.

6. Select the newly added Uipickerview control, hold down controls, drag to the file ' s owner icon, select Delegate and DataSource in the pop-up menu:

Open Assistant Editor, make sure that the ViewController.h is open, and then pull the string from the small circle in front of the picker property to the Uipickerview control:

Again, pull the small circle from the front of the buttonpressed method to the "select" button.

7. Operation:

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.