はiOSアプリの入力としては非常に便利ではあるのですが、
設定がややこしいので最初は戸惑います。私は下記のサイト
を参考にさせていただきました。
[iPhone]UIPickerViewのdatasourceとdelegateを実装する
1.まずはViewにPickerViewを貼付けます。
2.ViewControllerにPickerViewのDelegateとDataSourceを
追加します。
@interface KukuViewController : UIViewController{
3.controlを押しながらUIPickerViewDataSourceをクリック
するとメニューが出ます。そこでJump to Definitionを
選択します。(XCODE4ではダブルクリックが効きません
でした。)
@protocol UIPickerViewDataSource
@required
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
@end
4.requiredとなっている2つをコピーし、ヘッダにペース
トします。最初のものがPickerViewを何行にするかで、
次のものが各行の選択肢がいくつずつあるかです。
5.同様にcontrolを押しながらUIPickerViewDelegateをク
リックし、Jump to Definitionを選択します。
@protocol UIPickerViewDelegate
@optional
// returns width of column and height of row for each component.
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component;
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component;
// these methods return either a plain UIString, or a view (e.g UILabel) to display the row for the component.
// for the view versions, we cache any hidden and thus unused views and pass them back for reuse.
// If you return back a different object, the old one will be released. the view will be centered in the row rect
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view;
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component;
6.こちらはOptionalなので何を選んでもいいのですが、
PickerViewの選択肢のリストを設定するために
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
をヘッダにコピー&ペーストします。
7.DataSourceとDelegateをFile's Ownerに関連づけます。
xibを選択し、Interface BuilderでPickerViewを選択し
ます。Connections inspectorでそれぞれの右にある○
からFile's Ownerまでドラッグします。
8.ソースの部分を記述します。まずは列の設定。今回は
1列のみにします。
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
9:選択肢の数を設定します。
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
if (component == 0) {
//3行あるとする。
return 3;
}
//エラー処理
return 0;
}
10.次に選択肢の中身ですが、私はうまい方法がわからな
いので- (void)viewDidLoadにベタに設定しています。
- (void)viewDidLoad{
pickerStr[0] = @"First";
pickerStr[1] = @"Second";
pickerStr[2] = @"Third";
こうしておけば後でローカライズするのも簡単です。
(もっとうまい方法があるかもしれませんが)
11.PickerViewに代入します。
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component == 0) {
pickerStr[row];
}
}
これで実装できたはずです。
Pickerの内容を取り出すには、
int rowIndex = [pickerView selectedRowInComponent:0]
でインデックスを取得し、配列から取得します。


