首页 文章

了解UIPickerView的工作原理

提问于
浏览
1

相当新的,我需要一只手了解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 回答

  • 1

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

    你必须自己离开这个 .

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

    请注意,这对于iOS的任何常用委托方法都有效,它是pickerview的numberOfRows,或者是tableview,或者是collectionView,或者是参数中包含视图的任何委托方法 .

    容易理解的方法是将您的pickerview作为您的类(或属性)的字段,并简单地将参数与它进行比较 .

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

相关问题