您的位置:首页 > 产品设计 > UI/UE

UIPickerView的简单使用

2016-02-18 11:26 381 查看
首先初始化几个全局变量方便使用:

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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: