我注意到没有委托来观察UIDatePicker中的更改。有没有办法检测何时在选择器中进行更改而不确认任何内容,例如它旋转并落在我希望能够检测到的新数字上的那一刻。我想到了关键的价值观察,但我不认为那里有一个现场变化的财产
答案 0 :(得分:64)
您需要将UIControlEventValueChanged
事件添加到您的UIDatePicker以处理日期更改:
[myDatePicker addTarget:self action:@selector(dateIsChanged:) forControlEvents:UIControlEventValueChanged];
然后执行:
- (void)dateIsChanged:(id)sender{
NSLog(@"Date changed");
}
答案 1 :(得分:42)
转到IB并从UIDatePicker
拖动到.h文件。然后选择
在你的.m文件中处理你想要的内容; XCode将为您添加以下方法。
答案 2 :(得分:2)
以下是符合KVO标准的日期选择器的提案:
@interface LNKVODatePicker : UIDatePicker
@end
@implementation LNKVODatePicker
- (void)willMoveToWindow:(UIWindow *)newWindow
{
[super willMoveToWindow:newWindow];
[self removeTarget:self action:@selector(_didChangeDate) forControlEvents:UIControlEventValueChanged];
if(newWindow != nil)
{
[self addTarget:self action:@selector(_didChangeDate) forControlEvents:UIControlEventValueChanged];
}
}
- (void)dealloc
{
[self removeTarget:self action:@selector(_didChangeDate) forControlEvents:UIControlEventValueChanged];
}
- (void)_didChangeDate
{
[self willChangeValueForKey:@"date"];
[self didChangeValueForKey:@"date"];
}
@end
答案 3 :(得分:1)
Swift 4.2 | Xcode 10.1
@objc func handleDatePicker(_ datePicker: UIDatePicker) {
textField.text = datePicker.date.formatted
}
override func viewDidLoad() {
super.viewDidLoad()
datePicker.addTarget(self, action: #selector(handleDatePicker), for: .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)
}
}