美文网首页
Swift 设置UIDatePicker键盘输入日期

Swift 设置UIDatePicker键盘输入日期

作者: jsone | 来源:发表于2020-02-27 15:25 被阅读0次

    1、声明datePicker属性

    lazy var datePicker: UIDatePicker = {
        let picker = UIDatePicker.init()
        picker.datePickerMode = .date
        picker.date = Date.init()
        picker.locale = Locale.init(identifier: "zh")
        picker.maximumDate = Date.init()
        return picker
    }()
    

    2、设置输入框的键盘为datePicker

    // 设置datePicker键盘
    productionDateTextField.inputView = datePicker;
    

    3、设置键盘的工具栏

    // 设置工具栏
    let toolbar = UIToolbar.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: view.frame.width, height: 44)))
    let cancelInputItem = UIBarButtonItem.init(title: "取消", style: .plain, target: self, action: #selector(cancelInputAction))
    let doneInputItem = UIBarButtonItem.init(title: "完成", style: .plain, target: self, action: #selector(doneInputAction))
    let spaceItem = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    toolbar.items = [cancelInputItem, spaceItem, doneInputItem]
    productionDateTextField.inputAccessoryView = toolbar
    

    4、添加工具栏按钮的点击方法

    // 取消输入
    @objc func cancelInputAction() -> Void {
        productionDateTextField.resignFirstResponder()
    }
    // 输入完成
    @objc func doneInputAction() -> Void {
        productionDateTextField.resignFirstResponder()
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        productionDateTextField.text = dateFormatter.string(from: datePicker.date)
    }
    
    UIDatePiker键盘

    相关文章

      网友评论

          本文标题:Swift 设置UIDatePicker键盘输入日期

          本文链接:https://www.haomeiwen.com/subject/euzthhtx.html