在swift中,我以编程方式声明了textField。
override func viewDidLoad() {
super.viewDidLoad()
textField3.delegate = self
textField3.returnKeyType = UIReturnKeyType.Next;
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.addTarget(self, action: Selector("handleDatePicker:"), forControlEvents: UIControlEvents.ValueChanged)
textField3.inputView = datePicker
}
func handleDatePicker(sender: UIDatePicker) {
textField3.text = dateFormatter.stringFromDate(sender.date)
}
我发现所有其他问题与这个与界面构建器的处理相似,并没有帮助。我将如何以编程方式修复此问题?
Xcode 9•Swift 4
@objc func handleDatePicker(_ datePicker: UIDatePicker) {
textField3.text = datePicker.date.formatted
}
override func viewDidLoad() {
super.viewDidLoad()
datePicker.addTarget(self, action: #selector(handleDatePicker), forControlEvents: .valueChanged)
}
extension Date {
static let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
return formatter
}()
var formatted: String {
return Date.formatter.string(from: self)
}
}
Swift 3版@Leo Dabus回答:
func handleDatePicker(sender: UIDatePicker) {
textField3.text = datePicker.date.formatted
}
override func viewDidLoad() {
super.viewDidLoad()
datePicker.addTarget(self, action: #selector(handleDatePicker(sender:)), for: UIControlEvents.valueChanged)
}
extension Date {
var formatted: String {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE, dd MMM yyyy HH:mm:ss Z"
return formatter.string(from: self as Date)
}
}
在,斯威夫特4 确认到UITableViewDelegate make txtFChequeDate.delegate = self
func textFieldDidBeginEditing(_ textField: UITextField) {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .date
txtFChequeDate.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
if txtFChequeDate.text == "" {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
txtFChequeDate.text = dateFormatter.string(from: Date())
}
}
@objc func handleDatePicker(sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMM yyyy"
txtFChequeDate.text = dateFormatter.string(from: sender.date)
}