我试图在同一个viewController上有两个不同的date pickerViews,并让它们代表不同的数据。我尝试了不同的方法来执行此操作,但是两个日期选择器视图都显示相同的数据,但不能将它们全部放在一起。我是快速编程的新手。任何帮助都是极好的!
@IBOutlet weak var EventStart: UITextField!
var datepicker = UIDatePicker()
var datepicker2 = UIDatePicker()
@IBOutlet weak var EventEnd: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
createDatePicker()
Event.delegate = self
eventName.delegate = self
// Do any additional setup after loading the view.
}
func createDatePicker(){
datepicker.datePickerMode = .dateAndTime
datepicker2.datePickerMode = .dateAndTime
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
toolbar.setItems([doneButton], animated: false)
EventEnd.inputAccessoryView = toolbar
EventEnd.inputView = datepicker2
EventStart.inputAccessoryView = toolbar
EventStart.inputView = datepicker
}
func donePressed(){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
EventStart.text = dateFormatter.string(from: datepicker.date)
EventEnd.text = dateFormatter.string(from: datepicker2.date)
print(EventStart)
print(EventEnd)
self.view.endEditing(true)
}
最佳答案
@IBOutlet weak var EventStart: UITextField!
var datepicker = UIDatePicker()
var datepicker2 = UIDatePicker()
@IBOutlet weak var EventEnd: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.addDatePicker(datepicker, textfield:EventStart , selector: #selector(ViewController.donePressed))
self.addDatePicker(datepicker2 , textfield:EventEnd ,selector: #selector(ViewController.donePressed2))
// Do any additional setup after loading the view.
}
func addDatePicker(_ datepicker : UIDatePicker, textfield: UITextField, selector: Selector) {
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action:selector)
toolbar.setItems([doneButton], animated: false)
textfield.inputAccessoryView = toolbar
textfield.inputView = datepicker
}
func donePressed(){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
EventStart.text = dateFormatter.string(from: datepicker.date)
print(EventStart)
self.view.endEditing(true)
}
func donePressed2(){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
EventEnd.text = dateFormatter.string(from: datepicker2.date)
print(EventEnd)
self.view.endEditing(true)
}
关于ios - 如何在同一UIView中快速创建自定义UI日期选择器 View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45435401/