我在使用 Swift 4.0 的 Xcode 10、iOS 12.0.1 中取得了以下成功:
使用其他答案作为指导,我最终让UITextField
s 代表回应:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if let _ = textField.inputView as? UIDatePicker {
//In my case I had more than one text field who's delegate would fire this method
//So I checked to see if the input view was a date picker before continuing
//If you have only one "delegated" text field then there's probably
//no need for a check
perform(#selector(setDatePicker), with: nil, afterDelay: 0)
}
return true
}
@objc func setDatePicker() {
Thread.doBlockOnMainThread {
self.theTimePicker.countDownDuration = 1000 //or whatever
}
}
哪里Thread.doBlockOnMainThread(_)
是:
extension Thread {
class func doBlockOnMainThread(_ block: () -> Void) {
if !Thread.isMainThread {
DispatchQueue.main.sync(execute: {
block()
})
} else {
block()
}
}
}
顺便说一句,我发现不仅是UIDatePicker
第一个出现时,而且用户错误地尝试将倒计时值设置为零时也是如此。DatePicker 会自动移动到1
预期的位置,但是下一个值更改也不会触发所需的目标。