iOS选择器(Pickers)

最后更新于:2022-03-26 23:15:31

选择器的使用

选择器是一个可滚动视图,用于选取列表项中的值。

重要的属性

  • delegate
  • dataSource

重要的方法

- (void)reloadAllComponents
- (void)reloadComponent:(NSInteger)component
- (NSInteger)selectedRowInComponent:(NSInteger)component
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component
  animated:(BOOL)animated

修改 ViewController.h

我们将添加一个文本字段、选择器视图和一个数组。

我们将采用UITextFieldDelegate、UIPickerViewDataSource、UIPickerViewDelegate的协议。ViewController.h文件代码如下所示:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
<UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
{
    
    UITextField *myTextField;
    UIPickerView *myPickerView;
    NSArray *pickerArray;
}
@end

添加自定义方法 addPickerView

-(void)addPickerView{
    pickerArray = [[NSArray alloc]initWithObjects:@"Chess",
    @"Cricket",@"Football",@"Tennis",@"Volleyball", nil];
    myTextField = [[UITextField alloc]initWithFrame:
    CGRectMake(10, 100, 300, 30)];
    myTextField.borderStyle = UITextBorderStyleRoundedRect;
    myTextField.textAlignment = UITextAlignmentCenter;
    myTextField.delegate = self;
    [self.view addSubview:myTextField];
    [myTextField setPlaceholder:@"Pick a Sport"];
    myPickerView = [[UIPickerView alloc]init];
    myPickerView.dataSource = self;
    myPickerView.delegate = self;
    myPickerView.showsSelectionIndicator = YES;
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] 
    initWithTitle:@"Done" style:UIBarButtonItemStyleDone 
    target:self action:@selector(done:)];
    UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:
    CGRectMake(0, self.view.frame.size.height-
    myPickerView.frame.size.height-50, 320, 50)];
    [toolBar setBarStyle:UIBarStyleBlackOpaque];
    NSArray *toolbarItems = [NSArray arrayWithObjects: 
    doneButton, nil];
    [toolBar setItems:toolbarItems];
    myTextField.inputView = myPickerView;
    myTextField.inputAccessoryView = toolBar;

}

执行委托,如下所示:

#pragma mark - Text field delegates

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    if ([textField.text isEqualToString:@""]) {
        [self dateChanged:nil];
    }
}
#pragma mark - Picker View Data source
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView 
 numberOfRowsInComponent:(NSInteger)component{
    return [pickerArray count];
}

#pragma mark- Picker View Delegate

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
 (NSInteger)row inComponent:(NSInteger)component{
    [myTextField setText:[pickerArray objectAtIndex:row]];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:
  (NSInteger)row forComponent:(NSInteger)component{
    return [pickerArray objectAtIndex:row];
}

在ViewController.m修改viewDidLoad,如下所示:

(void)viewDidLoad
{
   [super viewDidLoad];
   [self addPickerView];
}

输出

现在当我们运行该应用程序我们会看到下面的输出:

pickerOutput1

文本选择器视图如下所示,我们可以选取我们需要的值:

pickerOutput2