CS356 UIPickerView Tutorial In this tutorial you will add a Picker

advertisement
CS356 UIPickerView Tutorial
In this tutorial you will add a Picker View object to the Tutorial 1 project that will allow the user
to choose from an array of strings. There is nothing to turn-in for this tutorial. However,
completing it will make Lab 4 much easier.
1. Begin with the completed Tutorial 1 Increment project.
2. Add an NSMutableArray property to the model class and initialize it to contain the strings
“Apple”, “Orange”, “Pear”, and “Peach”.
3. Our picker view object is going to need to know how many strings there are in the model
array. Add an instance method to IncModel that returns that value. I declared mine as:
- (NSUInteger) numStrings;
It will also need to know what string is at each index; add an instance method that returns the
appropriate string given an index. I declared mine as:
-(NSString*)stringAtIndex:(int) index
4. Next we want to turn our ViewController into a delegate and data source for a UIPickerView
object. The first step is to add the appropriate protocols to our View Controller header:
@interface PrizePickerViewController :
UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
5. In Storyboard, add a Picker View object to the View below the existing labels and buttons.
Make sure that Shows Selection Indicator and User Interaction Enabled are both checked in
the Attributes Inspector pane (they should be by default).
6. We now want to connect the Picker View delegate and data source to the View Controller.
Note the icons at the top of the Storyboard view; the leftmost icon represents the View
Controller. Right-Click on the Picker View object and connect both the delegate and
dataSource to the ViewController icon.
Page 1! of 2!
6. Next we need to implement the two methods required by the UIPickerViewDelegate protocol,
pickerView:didSelectRow:inComponent: and pickerView:titleForRow:forComponent: in
our ViewController. Refer to the completed example source code.
7. Add a label and outlet to display the Picker View choice.
8. Finally we need to implement the two methods required by the UIPickerViewDataSource
protocol in our ViewController, numberOfComponentsInPickerView: and
pickerView:numberOfRowsInComponent:. Again refer to the source code in the completed
application.
9. Run your application.
Page 2! of 2!
Download