ios 观察 UIDatePicker 的变化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11866712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Observing change in UIDatePicker
提问by Chris
I noticed that there is no delegate to observe changes in UIDatePicker. Is there a way to detect when a change is made in the picker without confirming anything, like the moment it spins and lands on a new number I want to be able to detect that. I thought about key value observing, but I don't think there's a property that changes on the spot
我注意到在 UIDatePicker 中没有观察变化的委托。有没有一种方法可以在不确认任何内容的情况下检测选择器中何时发生更改,例如它旋转并落在新数字上的那一刻,我希望能够检测到这一点。我想过关键值观察,但我认为没有当场改变的属性
回答by chroman
You need to add to your UIDatePicker the UIControlEventValueChanged
event to handle date changes:
您需要将UIControlEventValueChanged
事件添加到 UIDatePicker以处理日期更改:
[myDatePicker addTarget:self action:@selector(dateIsChanged:) forControlEvents:UIControlEventValueChanged];
Then the implementation:
然后实现:
- (void)dateIsChanged:(id)sender{
NSLog(@"Date changed");
}
回答by Dustin
Go to IB and drag from the UIDatePicker
to your .h file. Then select
转到 IB 并从UIDatePicker
.h 文件中拖动。然后选择
Handle this however you want in your .m file; XCode will add the method below for you.
在 .m 文件中根据需要处理此问题;XCode 将为您添加以下方法。
回答by Leo Natan
Here is a proposal for a KVO-compliant date picker:
这是一个符合 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
回答by Argus
Swift 4.2 | Xcode 10.1
斯威夫特 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)
}
}