【问题标题】:display done button on UIPickerview在 UIPickerview 上显示完成按钮
【发布时间】:2014-01-19 22:14:47
【问题描述】:

我在viewDidLoad方法中写了如下代码:

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

并调用此方法隐藏选择器视图

- (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];
}

我的问题是我想在选择器视图上显示一个“完成”按钮,并且选择器视图应该在按钮单击时隐藏。

【问题讨论】:

    标签: ios objective-c uipickerview


    【解决方案1】:

    您可以使用此代码,

    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;
    

    并为changeDateFromLabel:设置按钮操作方法

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

    【讨论】:

    • 你能看到工具栏吗?
    • 我需要更改 CGRectMake(0,0,320,44) @sathiamoorthy
    • 我尝试使用 pickerView.inputAccessoryView = toolBar;但它给出了只读属性@sathiamoorthy的错误分配
    • 试试这个,对我有用。 yourUITextField.inputView = pickerView; yourUITextField.inputAccessoryView = 工具栏; toolBar 是文本字段的输入附件视图的一部分,而不是选择器视图。
    • 栏和按钮出现,但按钮不可点击,就像透明的东西覆盖它一样。 InputAccesoryView 是只读的。
    【解决方案2】:

    您需要使用 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];
        }
    }
    

    【讨论】:

      【解决方案3】:
       #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
       {
      
      
       }
      

      【讨论】:

        【解决方案4】:

        应将带有“完成”按钮的UIToolbar 添加到成为第一响应者的视图的inputAccessoryView。由于UIView 类继承自UIResponder,因此任何视图都可能包含inputViewinputAccessoryView。因此,您可以使用 UIResponder 的键盘显示/隐藏动画附带的默认动画行为,而不是以编程方式手动执行动画。

        1. 子类化 UIView 并覆盖 inputViewinputAccessoryView 属性并将它们设为 readwrite。在此示例中,我将继承 UITableViewCell

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

          // FirstResponderTableViewCell.m
          - (BOOL)canBecomeFirstResponder {
              return YES;
          }
          
        3. 在您的视图控制器中,创建并分配选择器视图和输入辅助工具栏

          // 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. 不要忘记在需要时将第一响应者分配给视图(例如内部 - tableView:didSelectRowAtIndexPath:

          [self.myFirstResponderTableViewCell becomeFirstResponder];
          

        希望这会有所帮助。

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

        【讨论】:

          【解决方案5】:

          试试这个。

          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/

          【讨论】:

          • 如果我不使用 textField 而是在 IBAction 上使用 open picke 怎么办
          【解决方案6】:

          您可以创建视图并使用“完成”按钮和 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];
          }
          

          【讨论】:

          • 这是我猜的正确方法。 sathiamoorthy 的答案无法正常工作,因为完成按钮不起作用。
          【解决方案7】:

          复制粘贴解决方案!

          这适用于 iOS 10(可能还有其他版本)我在 2017 年 9 月 4 日编写了这段代码。

          我需要结合其他答案来获得我想要的,这是一个Cancel 按钮、Done 按钮,以及一个将在点击按钮时显示/隐藏的选择器视图。忽略我的屏幕截图在选择器中只有一项的事实。我的数组中只有一项。我已经测试了多个项目,效果很好。

          免责声明!我已经测试并使用了这段代码。我在示例中概括了名称,因此如果我错过了一个并且它们的属性名称不对齐,我提前道歉。

          为了让点击按钮时出现pickerView,您需要在视图控制器的任何位置创建一个dummyTextField(类型为UITextField。这是因为UIPickerView' s 旨在与 UITextFields 一起使用。为了模拟选择器的显示和隐藏,您的按钮点击需要调用 dummyTextField 的 becomeFirstResponderresignFirstResponder 方法。(示例如下)

          第一步

          创建自定义数据源类。 MyObj 是您希望在选取器中显示项目的类。

          在.h中:

          #import <UIKit/UIKit.h>
          @class myObj;
          
          @interface PickerDataSource : NSObject <UIPickerViewDataSource, UIPickerViewDelegate>
          @property (nonatomic, strong) MyObj *selectedObject;
          @end
          

          在.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
          

          第二步在您的视图控制器中,导入自定义数据源、委托和设置属性:(您必须包含文本字段委托!)

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

          第三步

          在您的viewDidLoad 中,调用[self 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];
          }
          

          第五步

          创建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];
          }
          

          第六步

          配置PickerDataSource,使其从源数组中获取您想要显示的数据。

          第 7 步

          点击Run

          【讨论】:

            【解决方案8】:

            在 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
              }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多