了解 UIPickerView 的工作原理

Understanding how UIPickerView works

相当新,我需要帮助理解 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;
}

其中returns果然五个问号。然后我可以继续创建一个数组来填充这些行等......但是我接下来添加另一个 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?谢谢

对于两个 PickerView,你只有一个委托方法;这是我不喜欢 iOS 的地方,但你真的别无选择。

你必须if-statement自己摆脱这个。

委托方法中的pickerView参数是指定行数的pickerview。

请注意,这对 iOS 的任何常用委托方法都是有效的,无论是 pickerview 的 numberOfRows、tableview、collectionView 还是任何在参数中具有视图的委托方法.

简单易懂的方法是将您的 pickerview 作为 class(或属性)的字段,然后简单地与参数进行比较。

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