首先初始化几个全局变量方便使用:
NSArray *showDataListTitle;
NSArray *showDataListContent;
NSString *titleStr;
NSString *contentStr;
UILabel *showLabel;
倒入代理
<UIPickerViewDataSource,UIPickerViewDelegate>
初始化:
UIPickerView *pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 100, 320, 216)];
// 挂上代理
pickerView.dataSource = self;
pickerView.delegate = self;
[self.view addSubview:pickerView];
//这里两个数组事要显示的数组
showDataListTitle = [[NSArray alloc]initWithObjects:@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",@"周日",nil];
showDataListContent = [[NSArray alloc]initWithObjects:@"一",@"二",@"三",@"四",@"五",@"六",@"日",nil];
showLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 20, 100, 50)];
[self.view addSubview:showLabel];
//代理方法
//pickerView的列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
//pickerView每列的个数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component==0) {
return [showDataListTitle count];
}
return [showDataListContent count];
}
//每列的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
if (component == 1) {
return 40;
}
return 180;
}
// 返回选中的行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
titleStr = [showDataListTitle objectAtIndex:row];
} else {
contentStr = [showDataListContent objectAtIndex:row];
}
//将选中的内容显示在label上
showLabel.text = [NSString stringWithFormat:@"%@ %@",titleStr,contentStr];
}
//返回当前行的内容,此处是将数组中数值添加到滚动的那个显示栏上
-(NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component == 0) {
return [showDataListTitle objectAtIndex:row];
} else {
return [showDataListContent objectAtIndex:row];
}
}
如果没有上面这个方法界面的显示效果为:
![这里写图片描述](http://img.blog.csdn.net/20160218113016882)
最后的显示效果为:
![这里写图片描述](http://img.blog.csdn.net/20160218113125363)