我试图让用户选择一个日期并让它显示在文本字段中。我在网上找到了这么多答案,但似乎都没有。我不知道他们是否过时了。我在" datePickerView.addTarget"上收到错误在选择器部分。当我运行应用程序时,我点击文本字段,键盘出现,这是我想要的。但是一旦我更改日期,应用程序就会崩溃。
任何帮助都会非常感激!
@IBAction func dateFieldEditing(sender: UITextField) {
let datePickerView:UIDatePicker = UIDatePicker()
datePickerView.datePickerMode = UIDatePickerMode.Date
sender.inputView = datePickerView
datePickerView.addTarget(self, action:Selector("handleDatePicker"),forControlEvents: UIControlEvents.ValueChanged)
}
func handleDatePicker (sender: UIDatePicker){
let formatter = NSDateFormatter()
formatter.dateStyle = .LongStyle
dateField.text = formatter.stringFromDate(sender.date)
}
答案 0 :(得分:0)
以下工作,假设您通过Interface Builder将UITextField和UIDatePicker绑定为IBOutlets。设置sender.inputView是不必要的。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var datePicker: UIDatePicker?
@IBOutlet weak var textField: UITextField?
func handleDatePicker (sender: UIDatePicker) {
let formatter = NSDateFormatter()
formatter.dateStyle = .LongStyle
textField!.text = formatter.stringFromDate(sender.date)
}
override func viewDidLoad() {
super.viewDidLoad()
self.datePicker!.datePickerMode = UIDatePickerMode.Date
datePicker!.addTarget(self, action:#selector(handleDatePicker(_:)), forControlEvents: UIControlEvents.ValueChanged)
}
}