Reference: Apple Developer Page |
|
Setup:
|
Create the connections to NMViewController.h file.
CTRL+drag from each of the three UI elements into the NMViewController.h file and release. For the UIPickerView element, when the popup appears, select "outlet" as an outlet type, and we’ll name the static label as “friendPrefix”, and the label for the UIPicker selection as “pickerSelection”. For the two labels, select “Outlet” as the connection type. We’ll call the UIPickerView “friendPicker”. |
Since we’ll be utilizing the built in methods of the UIPickerView, we’ll let Xcode know that within the interface line of our .h file. #import <UIKit/UIKit>; @interface ViewController : UIViewController <UIPickerViewDataSource,UIPickerViewDelegate>; @property (strong, nonatomic) IBOutlet UILabel *friendPrefix; @property (strong, nonatomic) IBOutlet UIPickerView *friendPicker; |
Data Source ImplementationWhile some Xcode UI elements already come preconfigured (like UIDatePicker), UIPickerview does require some coding to get the element to look right, and to function correctly. This is all done within the viewcontroller.m file. Create the array of names to populate our UIPickerView. Within the ‘viewDidLoad’ method in the viewcontroller.m file add a list of names: self.friendList = [[NSArray alloc] initWithObjects:@"Happy",@"Dopey",@"Doc",@"Bashful",@"Sleepy",@"Sneezy",@"Grumpy", nil]; |
UIPicker Setup
// returns the number of 'columns' to display. // returns the # of rows in each component The return in the numberOfRowsInComponent will just return the number of items in the friendList array. |
Delegate Implementation Configure the UIPickerView delegate that we defined in the .h file. Command+Click the UIPickerViewDelegate from viewcontroller.h will take you to a list of 3 delegate methods that we’ll define. The two that we’ll use for this example are: -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component } - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component |
Connecting Data Source and Delegate Connect our PickerView to the ViewController.
|
Adding to the Project |
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { // UIImage objects UIImage *Happy = [UIImage imageNamed:@"Happy.png"]; UIImage *Bashful = [UIImage imageNamed:@"Bashful.png"]; UIImage *Dopy = [UIImage imageNamed:@"Dopy.png"]; UIImage *Sleepy = [UIImage imageNamed:@"Sleepy.png"]; UIImage *Sneezy = [UIImage imageNamed:@"Sneezy.png"]; UIImage *Doc = [UIImage imageNamed:@"Doc.png"]; UIImage *Grumpy = [UIImage imageNamed:@"Grumpy.png"]; UIImage *John = [UIImage imageNamed:@"John.png"]; |
Add code to show image to each case: case 0: Repeat in each case. |
|