UIDatepicker工具栏在iOS Swift中无法在横向模式下工作

时间:2018-11-26 06:22:08

标签: ios iphone swift toolbar uidatepicker

横向和纵向应用程序均可工作。使用UIDatepicker选择日期。这里是UIDatepicker代码。

class ViewController: UIViewController {
    //Text Field Connection
    @IBOutlet weak var txtDatePicker: UITextField!
    //Uidate picker
    let datePicker = UIDatePicker()

    override func viewDidLoad() {
        super.viewDidLoad()
        //show date picker
        showDatePicker()
    }
    func showDatePicker(){
        //Formate Date
        datePicker.datePickerMode = .date

        //ToolBar
        let toolbar = UIToolbar();
        toolbar.sizeToFit()

        //done button & cancel button
        let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: "donedatePicker")
        let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.bordered, target: self, action: "cancelDatePicker")
        toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)

        // add toolbar to textField
        txtDatePicker.inputAccessoryView = toolbar
        // add datepicker to textField
        txtDatePicker.inputView = datePicker

    }
    func donedatePicker(){
        //For date formate
        let formatter = DateFormatter()
        formatter.dateFormat = "dd/MM/yyyy"
        txtDatePicker.text = formatter.string(from: datePicker.date)
        //dismiss date picker dialog
        self.view.endEditing(true)
    }
    func cancelDatePicker(){
        //cancel button dismiss datepicker dialog
        self.view.endEditing(true)
    }
}

UIDatePicker工具栏在纵向模式下可以正常工作。 enter image description here

在横向模式下更改应用程序,工具栏会隐藏。

enter image description here

如何解决此问题的帮助。

使用Google并引用一些链接:

  

Add a Done button within a pop-up datePickerView in Swift?

它不会对我锻炼。帮助我解决此问题。

2 个答案:

答案 0 :(得分:0)

我认为您需要为日期选择器设置框架。

self.datePicker = UIDatePicker(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))

答案 1 :(得分:0)

这似乎是iOS 11中的错误,而没有出现在iOS 12中。请在苹果开发者论坛中参考。

https://forums.developer.apple.com/thread/81650

修复:

func textFieldDidBeginEditing(_ textField: UITextField) {

    let item = textField.inputAssistantItem
    item.leadingBarButtonGroups = []
    item.trailingBarButtonGroups = []

    //Your code here....
}

也请一次查看此链接

Custom Keyboard InputAccessoryView not visible in iOS 11