一个TableViewController中的多个UIPickerView以编程方式

时间:2015-09-21 05:20:24

标签: ios xcode swift2 ios9 xcode7

我已经尝试了好几天,但我找不到一种有效的方法。我尝试设置它的方式将选择器视图加载为文本字段的键盘,这是我想要的,但它没有显示我已经放入其中的任何数据。有人可以帮我解决这个问题,或者给我一个链接和它的例子。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

    UIToolbar *toolbar = [[UIToolbar alloc] init];
    [toolbar setBarStyle:UIBarStyleBlack];
    [toolbar setBarTintColor:[UIColor colorWithRed:237.0/255.0 green:30.0/255.0 blue:36.0/255.0 alpha:1.0]];
    [toolbar sizeToFit];
    UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(resignKeyboard)];

    doneButton.tintColor = [UIColor whiteColor];

    NSArray *itemsArray = [NSArray arrayWithObjects:flexButton, doneButton, nil];
    [toolbar setItems:itemsArray];

    yourTextField.inputAccessoryView = toolbar;
    UIPickerView *categoryPicker   = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 210, 320, 216)];
    categoryPicker.backgroundColor = [UIColor whiteColor];
    categoryPicker.delegate = self;
    categoryPicker.dataSource = self;
    categoryPicker.tag = 1;
    yourTextField.inputView  = categoryPicker;

在viewdidappear中编写完所有代码后,实现pickerview的委托和数据源

pragma mark -UIPickerView Delegate和DataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return  1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return  yourDataSource.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [yourDataSource objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    yourTextField.text = [yourDataSource objectAtIndex:row];
}

并为完成按钮实现一个选择器

- (void)resignKeyboard
{
    [bloodGroupField resignFirstResponder];
}