【问题标题】:How to add UIDatePicker in UIAlertController in iOS8?如何在 iOS8 的 UIAlertController 中添加 UIDatePicker?
【发布时间】:2014-10-13 13:18:03
【问题描述】:

我正在开发一个已经随 iOS-7 发布的项目。但现在由于操作表出现问题,所以我现在正在实现 UIAlertController。以下是我使用 UIPicker 显示 UIAlertController 的代码。

alertController = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];

        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:alertAction];
        [alertController addAction:alertAction];
        [alertController addAction:alertAction];
        [alertController addAction:alertAction];
        [pickerToolbar setFrame:CGRectMake(0, 0, self.view.frame.size.width-20, 44)];
        [alertController.view addSubview:pickerToolbar];
        [alertController.view addSubview:picker];

        [alertController.view setBounds:CGRectMake(0, 0, self.view.frame.size.width, 485)];
        [self presentViewController:alertController animated:YES completion:nil];

但我无法在其中添加日期选择器。它与普通选择器不同,并且应用程序挂起。请为在 UIAlertController 中添加 UIDatePicker 的任何示例代码提供建议。提前致谢

【问题讨论】:

    标签: ios uidatepicker uiactionsheet uipicker uialertcontroller


    【解决方案1】:

    Apple 一直不鼓励将 UIDatePicker 添加到操作表。自 iOS 7 以来,Apple 引入了内联日期选择器的使用(查看它在日历应用程序中是如何完成的)。

    如果您设法使用 UIAlertController 破解了一个解决方法,它可能会在未来的 iOS 版本中再次崩溃。

    【讨论】:

    【解决方案2】:

    这里是 iOS9+ Swift 代码。

    将目标添加到您的日期按钮或其他视图。

         dateBtn.addTarget(self,action: #selector(YourViewController.dateSelect(_:)),forControlEvents: UIControlEvents.TouchDown) //my date button      
    
    
        func dateSelect(sender:UIButton)  {
    
    
        if (UI_USER_INTERFACE_IDIOM() == .Phone)
        {
    
            //init date picker
            self.datePicker = UIDatePicker(frame: CGRectMake(0, 0, self.view.frame.size.width,260))
            self.datePicker.datePickerMode = UIDatePickerMode.Date
    
            //add target
            self.datePicker.addTarget(self, action: #selector(YourViewController.dateSelected(_:)), forControlEvents: UIControlEvents.ValueChanged)
    
            //add to actionsheetview
            if(UIDevice.currentDevice().systemVersion >= "8.0")
            {
    
                let alertController = UIAlertController(title: "Date Selection", message:" " , preferredStyle: UIAlertControllerStyle.ActionSheet)
    
                alertController.view.addSubview(self.datePicker)//add subview
    
                let cancelAction = UIAlertAction(title: "Done", style: .Cancel) { (action) in
    
                    self.dateSelected(self.datePicker)
                    self.tableView.reloadData()
    
                }
    
                //add button to action sheet
                alertController.addAction(cancelAction)
    
    
                let height:NSLayoutConstraint = NSLayoutConstraint(item: alertController.view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 300)
                alertController.view.addConstraint(height);
    
                self.presentViewController(alertController, animated: true, completion: nil)
    
            }
    
    
        }
    
    }
    
    
    //selected date func
    func dateSelected(datePicker:UIDatePicker)
    {
    
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
    
        let currentDate = datePicker.date
        let day = currentDate.day()
        let month = currentDate.month()
        let year = currentDate.year()
    
        let date  = "\(day)/\(month)/\(year)"
    
        print(date)
    
    }
    

    【讨论】:

      【解决方案3】:

      这对我有用

      UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"\n\n\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
      UIDatePicker *picker = [[UIDatePicker alloc] init];
      [picker setDatePickerMode:UIDatePickerModeDate];
      [alertController.view addSubview:picker];
      [alertController addAction:({
          UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
              NSLog(@"OK");
              NSLog(@"%@",picker.date);
          }];
          action;
      })];
      UIPopoverPresentationController *popoverController = alertController.popoverPresentationController;
      popoverController.sourceView = sender;
      popoverController.sourceRect = [sender bounds];
      [self presentViewController:alertController  animated:YES completion:nil];
      

      【讨论】:

      • 在 iPhone 和 iOS 9 中,UIDatePickerUIPopoverPresnetationController 宽。应调整日期选择器的宽度。
      • 这里的sender 是什么?
      • 你在哪里使用popoverController
      【解决方案4】:

      在 Swift 2 中实现这一目标的简洁方式:

      let vc = UIAlertController(title: "Pickup time", message: nil, preferredStyle: .Alert)
              vc.addTextFieldWithConfigurationHandler({ (textfield) -> Void in
                  let datepicker = UIDatePicker()
                  // add delegate ... here
      
                  textfield.inputView = datepicker
              })
              vc.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
              vc.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
              presentViewController(vc, animated: true, completion: nil)
      

      【讨论】:

        【解决方案5】:

        swift3 中的@idris 代码

        //Function Start  
        func dateSelect()  {
        
            //init date picker
            let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 260))
            datePicker.datePickerMode = UIDatePickerMode.date
        
            //add target
            datePicker.addTarget(self, action: #selector(dateSelected(datePicker:)), for: UIControlEvents.valueChanged)
        
            //add to actionsheetview
            let alertController = UIAlertController(title: "Date Selection", message:" " , preferredStyle: UIAlertControllerStyle.actionSheet)
        
            alertController.view.addSubview(datePicker)//add subview
        
            let cancelAction = UIAlertAction(title: "Done", style: .cancel) { (action) in
                self.dateSelected(datePicker: datePicker)
            }
        
            //add button to action sheet
            alertController.addAction(cancelAction)
        
            let height:NSLayoutConstraint = NSLayoutConstraint(item: alertController.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 300)
            alertController.view.addConstraint(height);
        
            self.present(alertController, animated: true, completion: nil)
        
        }
        
        
        //selected date func
        @objc func dateSelected(datePicker:UIDatePicker) {
        
            let dateFormatter = DateFormatter()
            dateFormatter.dateStyle = DateFormatter.Style.short
        
            let currentDate = datePicker.date
        
            print(currentDate)
        
        }
        

        【讨论】:

          【解决方案6】:

          这是我在 iOS 7 和 iOS 8 上测试的代码

              - (id)initWithDatePicker:(NSString*)title parentView:(UIView*)parentView {
              self = [super init];
              if (self) {
                  datePickerView = [[UIDatePicker alloc] init];
                  datePickerView.datePickerMode = UIDatePickerModeDateAndTime;
                  if (IS_IOS8_AND_UP) {
                      alertViewController = [UIAlertController
                                             alertControllerWithTitle:EMPTY_STRING
                                             message:title
                                             preferredStyle:UIAlertControllerStyleActionSheet];
                      UIView* aboveBlurLayer = alertViewController.view.subviews[0];
                      [aboveBlurLayer addSubview:datePickerView];
                      [aboveBlurLayer setWidth:SCREEN_WIDTH - 16];
                      [datePickerView setWidth:SCREEN_WIDTH - 16];
                      [alertViewController.view setWidth:SCREEN_WIDTH - 16];
                      [alertViewController.view setBackgroundColor:[UIColor whiteColor]];
          
                      UIAlertAction* alertAction =
                      [UIAlertAction actionWithTitle:EMPTY_STRING
                                               style:UIAlertActionStyleDefault
                                             handler:nil];
                      [alertViewController addAction:alertAction];
                      [alertViewController addAction:alertAction];
                      [alertViewController addAction:alertAction];
                      [alertViewController addAction:alertAction];
          
                      [datePickerView setBackgroundColor:[UIColor whiteColor]];
                      [aboveBlurLayer addSubview:datePickerView];
                  } else {
                      actionSheet = [[UIActionSheet alloc] initWithTitle:title
                                                                delegate:self
                                                       cancelButtonTitle:nil
                                                  destructiveButtonTitle:nil
                                                       otherButtonTitles:nil];
          
                      [actionSheet addSubview:datePickerView];
                  }
          
                  [self addToolBar];
                  isDatePicker = YES;
                  parent = parentView;
              }
            return self;
          }
          

          在工具栏上,我有两个按钮“完成”和“取消”完成后,我通过代表发送回一个带有选定日期的呼叫,并在取消时关闭。此代码适用于 iOS 7 和 iOS 8

          【讨论】:

            【解决方案7】:

            这可以通过一些技巧来完成。 这是我目前使用的,几乎不需要维护。

            let alertController = UIAlertController(title: alertTitle, message: nil, preferredStyle: .actionSheet)
            
            let picker = UIDatePicker()
            picker.translatesAutoresizingMaskIntoConstraints = false
            alertController.view.addSubview(picker)
            alertController.view.heightAnchor.constraint(equalToConstant: 350).isActive = true
            picker.leadingAnchor.constraint(equalTo: alertController.view.leadingAnchor).isActive = true
            picker.trailingAnchor.constraint(equalTo: alertController.view.trailingAnchor).isActive = true
            picker.topAnchor.constraint(equalTo: alertController.view.topAnchor, constant: 10).isActive = true
            /// Add your actions here....
            

            【讨论】:

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