【UIPickerView自定义选择器控件】

/*@interface AppDelegate : UIResponder <UIApplicationDelegate,UIPickerViewDataSource,UIPickerViewDelegate>//协议


@property (strong, nonatomic) UIWindow *window;

@property(strong,nonatomic)NSArray *strings;

@property(strong,nonatomic)NSArray *strings1;

@property(strong,nonatomic)NSArray *images;

提升权限 定义属性*/


 

//创建自定义选择器

    UIPickerView *mypicker=[[UIPickerView alloc]initWithFrame:CGRectMake(0, 20, 320, 250)];

    mypicker.delegate=self;

    mypicker.backgroundColor=[UIColor whiteColor];

    //初始化面定格在哪一行

    [mypicker selectRow:2 inComponent:0 animated:YES];

    

    self.strings=[NSArray arrayWithObjects:@"11111", @"22222",@"33333",@"44444",@"55555",nil];

    self.strings1=[NSArray arrayWithObjects:@"aaaa",@"bbbb",@"cccc", nil];

    //图片数组

    self.images=[NSArray arrayWithObjects:[UIImage imageNamed:@"start1.jpg"],[UIImage imageNamed:@"start2.jpeg"], nil];

    [self.window addSubview:mypicker];

    

    return YES;

}

//设定列

-(NSInteger)numberOfComponentsInPickerView:(nonnull UIPickerView *)pickerView

{

    return 2;

}

 //设定行

-(NSInteger)pickerView:(nonnull UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component

{

    //控制每一列的行数

    if(component==0)

    return [self.strings count];

    else

        return self.strings1.count;

    //return self.images.count;

}

//选择器中行和列显示的内容

-(NSString *)pickerView:(nonnull UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component

{    // 控制每列中每行的输入,行数要与数组中的成员个数相等

    if(component==0)

       return self.strings[row];

    else

        return self.strings1[row];

}

//与上面相等效,但此方法可以设置字体颜色

/*-(UIView *)pickerView:(nonnull UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view

{

    UILabel *label=[[UILabel alloc]init];//无需设置大小

    if(component==0)

    label.text=self.strings[row];//设置颜色

    else

        label.text=self.strings1[row];

    label.textAlignment=NSTextAlignmentCenter;

    label.textColor=[UIColor redColor];

    return  label;

}*/

//设置行的高度,直接返回一个数字

-(CGFloat)pickerView:(nonnull UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component

{

    return 50;

}

//获得当前选择的行或列的信息

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

   

    if(component==0)

    NSLog(@"=%d,=%d,是:%@",component,row,self.strings[row]);

    else

        NSLog(@"=%d,=%d,是:%@",component,row,self.strings1[row]);

}

//在选择器上显图片,返回值是视图

/*-(UIView *)pickerView:(nonnull UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view

{

    

    UIImageView *vv=[[UIImageView alloc]init];//创建图片视图

        [vv setImage:self.images[row]];//设置图片视图显示的图片

    return vv;

}*/


你可能感兴趣的:(【UIPickerView自定义选择器控件】)