对UITextField问题使用UIDatePicker而不是Keyboard

时间:2015-08-22 06:11:22

标签: ios swift keyboard uitextfield uidatepicker

您好我在点击UIDatePicker时尝试显示UITextField而不是键盘,以便用户可以为事件提供开始和结束时间。我的代码工作但不是很好,而不是我想要的方式。

我的第一个问题是,只要您点击其中一个UITextField,UIDatePicker只会在第二次点击UITextField时出现。否则它会显示原始键盘。

我的第二个问题是,每当编辑UIDatePicker时,只有在编辑UITextField时才会更改UIDatePicker。我需要UITextFieldUIDatePicker打开后立即显示字符串,以便UITextFieldUIDatePicker上的内容保持同步。

这是我目前的代码:

override func viewDidLoad() {
super.viewDidLoad()
 var datePickerView  : UIDatePicker = UIDatePicker()
    datePickerView.datePickerMode = UIDatePickerMode.Time
    StartTimeTextField.inputView = datePickerView
    datePickerView.addTarget(self, action:
    Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)

    var datePickerView2  : UIDatePicker = UIDatePicker()
    datePickerView2.datePickerMode = UIDatePickerMode.Time
    EndTimeTextField.inputView = datePickerView2
    datePickerView2.addTarget(self, action: Selector("handleDatePicker2:"), forControlEvents: UIControlEvents.ValueChanged)
    }

func handleDatePicker(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "hh mm am pm"
    StartTimeTextField.text = dateFormatter.stringFromDate(sender.date)
}



func handleDatePicker2(sender: UIDatePicker) {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "hh mm am pm"
    EndTimeTextField.text = dateFormatter.stringFromDate(sender.date)
}

任何人都可以帮助我吗?感谢

1 个答案:

答案 0 :(得分:6)

为什么要通过动作更改键盘!

只需在viewDidLoad中添加您的代码:

var datePickerView  : UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Time
StartTimeTextField.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)

var datePickerView  : UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Time
EndTimeTextField.inputView = datePickerView
datePickerView.addTarget(self, action: Selector("handleDatePicker2:"), forControlEvents: UIControlEvents.ValueChanged)

并删除

之类的方法
@IBAction func