ios - 在多个 View Controller 中显示的通用或单个 uipickerview

标签 ios uipickerview uipickerviewdatasource uipickerviewdelegate

我想知道如何使通用/单个 UIPickerView 显示在多个 ViewControllers 中。

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

我知道如何像实现一样创建它并为它编写委托(delegate)..

但我不想在每个类中创建这些委托(delegate)并再次编写这些方法......

我做了什么..

我创建了一个新的文件,并用 UIPickerView 继承了它。并创建一个 NSArray 属性 以在其中显示。并且还实现了它的委托(delegate),但现在不知道该怎么做。

给我一​​些例子来制作一个通用的 UIPickerView 或帮助我创建它..

最佳答案

实现此目的的一种方法是创建一个带有完成处理程序的类,该处理程序创建选择器并充当其数据源和委托(delegate)。例如,在 .h 文件中,你可以这样做,

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

@interface RDPickerController : NSObject <UIPickerViewDataSource, UIPickerViewDelegate>

@property (strong,nonatomic) UIPickerView *picker;

-(instancetype)initWithCompletionHandler:(completionHandler) completion;

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

@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]);
}

在你的 Controller 类中,你可以像这样创建和使用选择器,

@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];
}

关于ios - 在多个 View Controller 中显示的通用或单个 uipickerview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25582973/

相关文章:

ios - UIPickerView:NSAttributedString 在 iOS 7 中不可用?

ios - 适用于iOS应用的GCM(Google云消息传递)

ios - 将 UIViewController 添加到 UIScrollView swift 3

ios - 将 UIPickerView 行标题链接到新的 View Controller

ios - UIPickerView pickerView :titleForRow:rowforComponent method not called

ios - PickerView 在黑色背景下不可见

ios - 是否可以修复抗锯齿 SKShapeNodes 的模糊性?

ios - 如何在解析表中排名

ios - 找不到我的应用程序崩溃的原因

uitableview - 是否有可能获得一个 .xib 窗口到选项卡式 Storyboard