用户按下按钮后如何在Swift中显示UIDatePicker?

时间:2016-10-26 18:15:02

标签: ios swift uidatepicker

在我的swift应用中,我有三个组成部分:textviewbuttonlabel。目前我处理键盘行为,所以当用户开始在textview中输入任何内容时(或者更确切地说 - 只需点击它),就会出现键盘。我使用以下代码处理它:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    NotificationCenter.default.addObserver(self, selector: 
           #selector(keyboardWillChangeFrame),
           name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}

然后我有方法keyboardWillChangeFrame

func keyboardWillChangeFrame(_ notification: Notification) {
    let endFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

    if(isKeyboardShown == true)
    {
        bottomConstraint.constant = view.bounds.height - endFrame.origin.y
        self.view.layoutIfNeeded()
        isKeyboardShown = false
    } else {
        bottomConstraint.constant = view.bounds.height - endFrame.origin.y
        self.view.layoutIfNeeded()
        isKeyboardShown = true
    }

}

工作正常。我希望在显示日期选择器时对约束做同样的事情 - 当用户按下按钮时,选择器应该出现在通常键盘出现的位置(因此屏幕向上移动,同时在底部显示选择器)然后标签可以显示所选日期。

你可以帮帮我吗?我添加了按钮操作的插座:

@IBAction func datePickerButtonAction(_ sender: AnyObject) {
    let datePickerView:UIDatePicker = UIDatePicker()

    datePickerView.datePickerMode = UIDatePickerMode.date

    textView.inputView = datePickerView

    datePickerView.addTarget(self, action: #selector(MapViewController.datePickerValueChanged), for: UIControlEvents.valueChanged)

}

func datePickerValueChanged(sender:UIDatePicker) {

    let dateFormatter = DateFormatter()

    //dateFormatter.dateStyle = DateFormatter.Style.MediumStyle

    //dateFormatter.timeStyle = DateFormatter.Style.NoStyle

    //print(dateFormatter.string(from: sender.date))

}

但没有任何反应,按钮不会显示选择器。我究竟做错了什么?

0 个答案:

没有答案