简体   繁体   English

在 UIPickerview 上显示完成按钮

[英]display done button on UIPickerview

I have written the following code in the viewDidLoad method:我在viewDidLoad方法中编写了以下代码:

categoryPickerView=[[UIPickerView alloc]init];
categoryPickerView.alpha = 0;
[self.view addSubview:categoryPickerView];
categoryPickerView.delegate=self;
categoryPickerView.tag=1;

and called this method to hide picker view并调用此方法来隐藏选择器视图

- (IBAction)hidePickerView:(id)sender {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.6];
    CGAffineTransform transfrom = CGAffineTransformMakeTranslation(0, 200);
    categoryPickerView.transform = transfrom;
    categoryPickerView.alpha = categoryPickerView.alpha * (-1) + 1;
    [UIView commitAnimations];
}

My problem is that I want to display a "Done" button on a picker view and the picker view should hide on button click.我的问题是我想在选择器视图上显示“完成”按钮,并且选择器视图应该在单击按钮时隐藏。

You can use this code, 你可以使用这段代码,

UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,320,44)];
[toolBar setBarStyle:UIBarStyleBlackOpaque];
UIBarButtonItem *barButtonDone = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
    style:UIBarButtonItemStyleBordered target:self action:@selector(changeDateFromLabel:)];
toolBar.items = @[barButtonDone];
barButtonDone.tintColor=[UIColor blackColor];
[pickerView addSubview:toolBar];
//(or)pickerView.inputAccessoryView = toolBar;

and set button action method for changeDateFromLabel: 并为changeDateFromLabel:设置按钮操作方法changeDateFromLabel:

-(void)changeDateFromLabel:(id)sender
{
   [[your UI Element] resignFirstResponder];
}

You can create view and add toolbar with "Done" button and UIPickerView as subviews 您可以使用“完成”按钮创建视图并添加工具栏,并使用UIPickerView作为子视图

- (void)createInputView {
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;

    UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 44)];
    [toolBar setBarStyle:UIBarStyleDefault];
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];

    UIBarButtonItem *barButtonDone = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                                  style:UIBarButtonItemStyleBordered
                                                                 target:self
                                                                 action:@selector(doneClicked)];
    toolBar.items = @[flex, barButtonDone];
    barButtonDone.tintColor = [UIColor blackColor];

    UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, toolBar.frame.size.height, screenWidth, 200)];
    picker.delegate = self;
    picker.dataSource = self;
    picker.showsSelectionIndicator = YES;


    UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, toolBar.frame.size.height + picker.frame.size.height)];
    inputView.backgroundColor = [UIColor clearColor];
    [inputView addSubview:picker];
    [inputView addSubview:toolBar];

    textField.inputView = inputView;
}

- (void)doneClicked {
    [textField resignFirstResponder];
}

You need to use the UIToolbar as the accessory view: Try with this: 您需要使用UIToolbar作为附件视图:尝试使用此:

#pragma mark - PickerView for Location Selection

- (UIPickerView *)locationsPicker {
    if ( locationsPicker == nil ) {
        locationsPicker = [[UIPickerView alloc] init];
        locationsPicker.delegate = self;
        locationsPicker.dataSource = self;
        locationsPicker.showsSelectionIndicator = YES;
    }
    return locationsPicker;
}

- (UIToolbar *)accessoryView {
    if ( accessoryView == nil ) {
        accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

        UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:
                                       UIBarButtonSystemItemDone
                                       target:self
                                       action:@selector(onLocationSelection)];
        [accessoryView setItems:[NSArray arrayWithObject:doneButton]];
    }
    return accessoryView;
}

- (void)onLocationSelection {
    NSInteger row = [self.locationsPicker selectedRowInComponent:0];
    if ( [Location isFirstResponder] ) {
       NSLog(@"%@", [listOfLocations objectAtIndex:row]);
        [Location resignFirstResponder];
    }
}

Copy-pasteable solution! 复制粘贴解决方案!

This works in iOS 10 (and probably other versions too) I wrote this code on 9/4/2017. 这适用于iOS 10(也可能是其他版本)我在9/4/2017写了这段代码。

I needed to combine other answers to get what I wanted, which was a Cancel button, Done button, and a picker view that would show/hide on the tap of a button. 我需要结合其他答案来获得我想要的东西,这是一个Cancel按钮, Done按钮,以及一个可以在按钮上显示/隐藏的选择器视图。 Ignore the fact that my screenshot only has one item in the picker.. I only have one item in my array. 忽略我的屏幕截图在选择器中只有一个项目的事实..我的数组中只有一个项目。 I've tested multiple items, it works fine. 我测试了多个项目,它运行正常。

在此输入图像描述

Disclaimer! 免责声明! I have tested and used this code. 我已经测试并使用了这段代码。 I generalized the names in my example, so I apologize in advance if I missed one and they property names don't line up. 我在我的例子中概括了名字,所以如果我错过了一个并且他们的属性名称没有排列,我会事先道歉。

In order to have a pickerView that appears on the tap of a button, you need to create a dummyTextField (of type UITextField anywhere in your view controller . This is because UIPickerView 's are designed to work with UITextFields. To mimic showing and hiding of the picker, your button taps need to call the dummyTextField's becomeFirstResponder and resignFirstResponder methods. (examples are below) 为了在按钮上显示一个pickerView,你需要在视图控制器的任何地方创建一个dummyTextField(类型为UITextField 。这是因为UIPickerView的设计与UITextFields一起工作。模仿显示和隐藏选择器,你的按钮点击需要调用dummyTextField的becomeFirstResponderresignFirstResponder方法。(例子如下)

Step one 第一步

Create a custom data source class. 创建自定义数据源类。 MyObj is the class you want to have items show up in the picker for. MyObj是您想要在选择器中显示项目的类。

In .h: 在.h:

#import <UIKit/UIKit.h>
@class myObj;

@interface PickerDataSource : NSObject <UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, strong) MyObj *selectedObject;
@end

In .m: 在.m:

#import "PickerDataSource.h"
#import "MyObj.h"

@implementation PickerDataSource

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.selectedObject = mySourceArray[row];
}

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

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

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return ((MyObj *)mySourceArray[row]).myTitle;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    int sectionWidth = 300;
    return sectionWidth;
}

@end

Step two In your view controller, import custom data source, delegate, and set properties: (You must include the text field delegate!) 第二步在视图控制器中,导入自定义数据源,委托和设置属性:( 必须包含文本字段委托!)

#import "PickerDataSource.h"

@interface MyViewController () <UIPickerViewDelegate, UITextFieldDelegate>
@property (strong, nonatomic) PickerDataSource *pickerDataSource;
@property (strong, nonatomic) UIPickerView *picker;
@property (strong, nonatomic) UITextField *dummyTextField;
@end

Step three 第三步

In your viewDidLoad , call [self setupPicker]; viewDidLoad ,调用[self setupPicker]; (you'll create this method next) (接下来你将创建这个方法)

Step four 第四步

Create setupPicker 创建setupPicker

- (void)setupPicker {
    // init custom picker data source
    self.pickerDataSource = [PickerDataSource new];
    // init custom picker
    self.picker = [UIPickerView new];
    // set the picker's dataSource and delegate to be your custom data source
    self.picker.dataSource = self.pickerDataSource;
    self.picker.delegate = self.pickerDataSource;
    self.picker.showsSelectionIndicator = YES;

    // next step is to write this configure method getting called here
    [self configurePickerSubviews];

    // lastly, add the dummyTextField to your view.
    [self.view addSubview:self.dummyTextField];
}

Step five 第五步

Create configurePickerSubviews 创建configurePickerSubviews

- (void)configurePickerSubviews {
    // A UIPickerView must be added as an inputView to a UITextField in order to be displayed on button tap
    // So you need to create a dummyTextField to do so.
    self.dummyTextField = [UITextField new];

    // Create a toolbar to add a done button
    UIToolbar *toolBar= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width,44)];
    [toolBar setBarStyle:UIBarStyleDefault];
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(locationPressed)];

    // Create a flex space so that done button will be right aligned
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(dismissPicker)];
    toolBar.items = @[cancel, flex, done];
    done.tintColor = [UIColor blackColor];

    [self.picker addSubview:toolBar];

    // Create an input view to add picker + done button as subviews
    UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.picker.frame.size.height + 44)];
    [self.picker setFrame:CGRectMake(0, 0, inputView.frame.size.width, inputView.frame.size.height)];
    inputView.backgroundColor = [UIColor clearColor];
    [inputView addSubview:self.picker];
    [inputView addSubview:toolBar];

    // Set custom inputView as container for picker view
    self.dummyTextField.inputView = inputView;

    // Hiding the textfield will hide the picker
    [self.dummyTextField setHidden:YES];
}

Step six 第六步

Configure the PickerDataSource so that it is fetching the data you want to display from your source array. 配置PickerDataSource以便从源阵列中获取要显示的数据。

Step 7 第7步

Click Run ! 单击Run

The UIToolbar with the 'Done' button should be added to the inputAccessoryView of the view that becomes first responder . 带有“完成”按钮的UIToolbar应该添加到成为第一响应者的视图的inputAccessoryView中。 As the UIView class inherits from UIResponder , any view can potentially contain an inputView and inputAccessoryView . 由于UIView类继承自UIResponder ,因此任何视图都可能包含inputViewinputAccessoryView So instead of manually performing the animations programmatically, you could use the default animation behaviour that comes with the UIResponder's keyboard show/hide animation. 因此,您可以使用UIResponder的键盘显示/隐藏动画附带的默认动画行为,而不是以编程方式手动执行动画。

  1. Subclass a UIView and override the inputView and inputAccessoryView properties and make them readwrite . 子类化UIView并覆盖inputViewinputAccessoryView属性并使它们成为readwrite In this example, I will subclass a UITableViewCell . 在这个例子中,我将子类化一个UITableViewCell

     // FirstResponderTableViewCell.h @interface FirstResponderTableViewCell : UITableViewCell @property (readwrite, strong, nonatomic) UIView *inputView; @property (readwrite, strong, nonatomic) UIView *inputAccessoryView; @end 
  2. Override canBecomeFirstResponder in your subclass' implementation. 在子类的实现中覆盖canBecomeFirstResponder

     // FirstResponderTableViewCell.m - (BOOL)canBecomeFirstResponder { return YES; } 
  3. In your view controller, create and assign the picker view and input accessory toolbar 在视图控制器中,创建并指定选取器视图和输入附件工具栏

     // MyViewController.m - (void)viewDidLoad { [super viewDidLoad]; UIPickerView *pickerView = [[UIPickerView alloc] init]; UIToolbar *accessoryToolbar = [UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)]; // Configure toolbar ..... // note: myFirstResponderTableViewCell is an IBOutlet to a static cell in storyboard of type FirstResponderTableViewCell self.myFirstResponderTableViewCell.inputView = pickerView; self.myFirstResponderTableViewCell.inputAccessoryView = accessoryToolbar; } 
  4. Don't forget to assign first responder to the view when required (eg inside - tableView:didSelectRowAtIndexPath: ) 不要忘记在需要时将第一响应者分配给视图(例如inside - tableView:didSelectRowAtIndexPath:

     [self.myFirstResponderTableViewCell becomeFirstResponder]; 

Hope this helps. 希望这可以帮助。

Reference: http://blog.swierczynski.net/2010/12/how-to-create-uipickerview-with-toolbar-above-it-in-ios/ 参考: http//blog.swierczynski.net/2010/12/how-to-create-uipickerview-with-toolbar-above-it-in-ios/

Try this. 试试这个。

UIPickerView *cityPicker = [[UIPickerView alloc] initWithFrame:CGRectZero];
cityPicker.delegate = self;
cityPicker.dataSource = self;
[cityPicker setShowsSelectionIndicator:YES];
txtText.inputView = cityPicker;
// Create done button in UIPickerView
UIToolbar*  mypickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
mypickerToolbar.barStyle = UIBarStyleBlackOpaque;
[mypickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(pickerDoneClicked)];
[barItems addObject:doneBtn];
[mypickerToolbar setItems:barItems animated:YES];
txtText.inputAccessoryView = mypickerToolbar;  // set the toolbar as input accessory view  for uitextfield, not the pickerview.

http://technopote.com/how-to-make-multiple-uipickerview-in-a-single-view/ http://technopote.com/how-to-make-multiple-uipickerview-in-a-single-view/

 #import "ViewController.h"

 @interface ViewController ()<UIPickerViewDelegate>
 {
UIPickerView *myPickerView;
NSArray *namesArray ;

 }
 @end

 @implementation ViewController

 -(void)viewDidLoad
 {
 [super viewDidLoad];
    namesArray=[[NSArray alloc]initWithObjects:@"a",@"b", nil];
   [self popoverWithInformation];


  }

 -(void)popoverWithInformation
 {
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];


UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(pickerCancel:)];
[barItems addObject:cancelBtn];

UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[barItems addObject:flexSpace];

UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(pickerDone:)];
[barItems addObject:doneBtn];



[pickerToolbar setItems:barItems animated:YES];


myPickerView = [[UIPickerView alloc] init];
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
CGRect pickerRect = myPickerView.bounds;
myPickerView.bounds = pickerRect;
myPickerView.frame = CGRectMake(0, 44, 320, 216);

UIView* popoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, 320, 300)];
popoverView.backgroundColor = [UIColor whiteColor];
[popoverView addSubview:myPickerView];

[popoverView addSubview:pickerToolbar];
[self.view addSubview:popoverView];
 }
 -(void)pickerView:(UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent:(NSInteger)component {


 }

 // tell the picker how many rows are available for a given component
 -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {

  return namesArray.count;
 }

 // tell the picker how many components it will have
 -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
 }

 // tell the picker the title for a given component
 -(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {




return namesArray[row];
 }

 // tell the picker the width of each row for a given component
 -(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
int sectionWidth = 300;

return sectionWidth;
 }

 -(void)pickerDone:(id)sender
 {


 }
 -(void)pickerCancel:(id)sender
 {


 }

In Swift 5 try this,在 Swift 5 中试试这个,

  func setToolBar() {
        let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44))
        toolBar.barStyle = UIBarStyle.default
        let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(self.donePicker))
        toolBar.setItems([doneButton],animated: false)
        toolBar.isUserInteractionEnabled = true
        doneButton.tintColor = UIColor.black
        picker.addSubview(toolBar)
      }  

  @objc func donePicker() {
    // hide keypad
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM