Observing change in UIDatePicker

蹲街弑〆低调 提交于 2019-12-05 08:26:47

问题


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


回答1:


Go to IB and drag from the UIDatePicker to your .h file. Then select

Handle this however you want in your .m file; XCode will add the method below for you.




回答2:


You need to add to your UIDatePicker the UIControlEventValueChanged event to handle date changes:

[myDatePicker addTarget:self action:@selector(dateIsChanged:) forControlEvents:UIControlEventValueChanged];

Then the implementation:

- (void)dateIsChanged:(id)sender{
     NSLog(@"Date changed");
}



回答3:


Here is a proposal for a KVO-compliant date picker:

@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



回答4:


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)
    }
}


来源:https://stackoverflow.com/questions/11866712/observing-change-in-uidatepicker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!