一种方法是创建一个带有完成处理程序的类,该处理程序创建选择器并充当其数据源和委托。例如,在 .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];
}