ios-UIPickerView基本使用

时间:2023-12-29 23:15:20
#import "ViewController.h"

@interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
{
NSArray *pickerArray;
}
@property (weak, nonatomic) IBOutlet UIPickerView *myPickerView; @end @implementation ViewController - (void)viewDidLoad
{
[super viewDidLoad];
_myPickerView.dataSource=self;
_myPickerView.delegate=self;
_myPickerView.showsSelectionIndicator=YES;
pickerArray=[NSArray arrayWithObjects:@"",@"",@"",@"",@"",@"",@"",@"",@"",@"", nil]; } - (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return ;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return pickerArray.count;
} -(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
CGRect rect=CGRectMake(, , [self pickerView:pickerView widthForComponent:row], [self pickerView:pickerView rowHeightForComponent:row]);
UIView *testView=[[UIView alloc]initWithFrame:rect];
[testView setBackgroundColor:[UIColor clearColor]];
[testView setOpaque:YES];
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(, , [self pickerView:pickerView widthForComponent:row]-16.0f, [self pickerView:pickerView rowHeightForComponent:row])];
[label setBackgroundColor:[UIColor clearColor]];
label.textAlignment=NSTextAlignmentCenter;
label.text=pickerArray[row];
switch (row)
{
case :
case :
{
testView.backgroundColor=component==?[UIColor greenColor]:[UIColor blueColor];
}
case :
{
testView.backgroundColor=component==?[UIColor brownColor]:[UIColor redColor];
}
break;
default:
{
testView.backgroundColor=component==?[UIColor grayColor]:[UIColor orangeColor];
}
break;
}
label.font=[UIFont boldSystemFontOfSize:14.0f];
[testView addSubview:label];
return testView;
} //可有可无
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return pickerArray[row];
}
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component;
{
return ;
}
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
return ;
} - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{ NSLog(@"row=%ld",row);
}

ios-UIPickerView基本使用