了解UIPickerView的工作原理

时间:2016-01-14 10:39:47

标签: objective-c uipickerview

相当新,我需要了解UIPickerViews。

我已经以编程方式为我的项目创建了一个UIPickerView:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIPickerView *myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 375, 200)];
    myPickerView.delegate = self;
    myPickerView.showsSelectionIndicator = YES;
    [self.view addSubview:myPickerView];   
}

然后为行数添加了一个方法:

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    NSUInteger numRows = 5;

    return numRows;
}

返回预期的五个问号。然后我可以继续创建一个数组来填充这些行等......但是我接下来会添加另一个UIPickerView:

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIPickerView *myPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 375, 200)];
    myPickerView.delegate = self;
    myPickerView.showsSelectionIndicator = YES;
    [self.view addSubview:myPickerView];

    UIPickerView *my2PickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 400, 375, 200)];
    my2PickerView.delegate = self;
    my2PickerView.showsSelectionIndicator = YES;
    [self.view addSubview:my2PickerView];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    NSUInteger numRows = 5;

    return numRows;
}

现在我有两个pickerview控制器,它们共有五行。我的问题是如何选择该方法适用的哪个pickerview,也可以解释为什么该方法适用于项目中的所有pickerview?感谢。

1 个答案:

答案 0 :(得分:1)

两个PickerView只有一个委托方法;这是我不喜欢iOS的东西,但你真的没有选择。

你必须自己if-statement

委托方法中的pickerView参数是分配了行数的选择器视图。

请注意,这适用于iOS的任何常用委托方法,无论是pickerview的numberOfRows,还是tableview,collectionView,还是参数中包含视图的任何委托方法。 / p>

易于理解的方法是将您的选择器视图作为您的类(或属性)的字段,并简单地将参数与其进行比较。

@interface ViewController ()
@property (weak, nonatomic) UIPickerView *_mySexyPickerView;
@property (weak, nonatomic) UIPickerView *_myOtherPickerView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _mySexyPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 200, 375, 200)];
    _mySexyPickerView.delegate = self;
    _mySexyPickerView.showsSelectionIndicator = YES;
    [self.view addSubview:_mySexyPickerView];

    _myOtherPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 400, 375, 200)];
    _myOtherPickerView.delegate = self;
    _myOtherPickerView.showsSelectionIndicator = YES;
    [self.view addSubview:_myOtherPickerView];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (pickerView == _mySexyPickerView){
         return 2;
    }

    if (pickerView == _myOtherPickerView){
         return 19;
    }
    return 0;
}