要在多个viewControllers中显示的通用或单个uipickerview

时间:2014-08-30 13:41:35

标签: ios uipickerview uipickerviewdatasource uipickerviewdelegate

我想知道如何制作通用/单UIPickerView以多个ViewControllers显示。

我想在多个ViewController中显示一个pickerView。现在我该如何创建呢。

我知道如何像工具一样创建它并为其编写代理..

但是我不想在每个班级中创建这些委托,并再次编写这些方法和agian ..

我做了什么..

我创建了一个新文件并使用UIPickerView继承它。并创建一个NSArray property以显示在其中。并且还实施了其代表,但现在还不知道如何去做。

向我展示制作通用UIPickerView或帮助我创建它的某种示例..

1 个答案:

答案 0 :(得分:2)

这样做的一种方法是创建一个带有完成处理程序的类,该处理程序创建选择器并充当其数据源和委托。例如,在.h文件中,您可以执行类似的操作,

typedef void(^completionHandler) (NSString *selectedString);

@interface RDPickerController : NSObject <UIPickerViewDataSource, UIPickerViewDelegate>

@property (strong,nonatomic) UIPickerView *picker;

-(instancetype)initWithCompletionHandler:(completionHandler) completion;

在.m文件中,实现您需要的任何数据源和委托方法,并在pickerView中调用完成块:didSelectRow:inComponent:方法,

@interface RDPickerController ()
@property (strong,nonatomic) NSArray *data;
@property (copy,nonatomic) completionHandler compBlock;
@end

@implementation RDPickerController


-(instancetype)initWithCompletionHandler:(completionHandler)completion {
    if (self = [super init]) {
        _picker = [UIPickerView new];
        _picker.delegate = self;
        _picker.dataSource = self;
        _data = @[@"One", @"Two", @"Three", @"Four", @"Five", @"Six", @"Seven", @"Eight", @"Nine", @"Ten"];
        _compBlock = completion;
    }
    return self;
}


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


-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.data.count;
}


-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return self.data[row];
}


-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.compBlock(self.data[row]);
}

在您的控制器类中,您可以创建和使用这样的选择器,

@interface ViewController ()
@property (strong,nonatomic) RDPickerController *pc;
@end

@implementation ViewController

- (IBAction)showPicker:(UIButton *)sender {
    self.pc = [[RDPickerController alloc] initWithCompletionHandler:^(NSString *selectedString) {
        NSLog(@"%@",selectedString);
        // do whatever with the returned data here
    }];

    [self.view addSubview:self.pc.picker];
}