如何为此选择器视图提供数据源

时间:2011-03-21 20:02:40

标签: iphone ios sdk uipickerview subview

这里我以编程方式添加了一个pickerview

 - (void)viewDidLoad {
        [super viewDidLoad];
        CGRect pickerFrame = CGRectMake(0,280,321,200);

        UIPickerView *myPickerView = [[UIPickerView alloc] init]; //Not sure if this is the proper allocation/initialization procedure

        //Set up the picker view as you need it

        //Set up the display frame
        myPickerView.frame = pickerFrame; //I recommend using IB just to get the proper width/height dimensions

        //Add the picker to the view
        [self.view addSubview:myPickerView];
    }

但是现在我需要实际让它显示内容并以某种方式找出它何时发生变化以及变更后的值。我该怎么做呢?

2 个答案:

答案 0 :(得分:18)

<。>在.h文件中放置此代码

@interface RootVC : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>

将数据源和委托分配给选择器

// this view controller is the data source and delegate
myPickerView.delegate = self;
myPickerView.dataSource = self;

使用以下委托和数据方法

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return 200;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 50;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *returnStr = @"";
    if (pickerView == myPickerView)
    {       
        returnStr = [[levelPickerViewArray objectAtIndex:row] objectForKey:@"nodeContent"];
    }

    return returnStr;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView == myPickerView)
    {
        return [levelPickerViewArray count];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

答案 1 :(得分:0)

您需要创建一个实现UIPickerViewDataSource协议的类,并将其实例分配给myPickerView.dataSource