本文介绍了当样式为 .compact 时,选择后关闭 UIDatePicker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Swift 的故事板应用程序.

Storyboard application using Swift.

如何在用户选择日期后关闭日历(当 UIDatePicker 样式为 .compact 时显示用于日期选择)?目前,用户需要点击日历外部才能关闭.我希望它在用户选择日期后自动关闭.

How can I close the calendar (presented for date selection when the UIDatePicker style is .compact) after a user selects a date? Currently, the user is required to tap outside the calendar for it to close. I want it to close automatically after a user has selected a date.

我已经尝试退出 UIDatePicker 的第一响应者,一旦收到日期更改的通知,就结束在表视图控制器中的编辑,读取另一个响应(此处),到目前为止没有任何东西对我有用.

I've tried resigning first responder of the UIDatePicker, ending editing in the table view controller once a notification is received that a date changed, reading another response (here) and so far nothing is working for me.

推荐答案

现在,您可以:

presentedViewController?.dismiss(animated: true, completion: nil)

override func viewDidLoad() {
    super.viewDidLoad()
    datePicker.addTarget(self, action: #selector(dateChanged), for: .valueChanged)
}

@objc private func dateChanged() {
    presentedViewController?.dismiss(animated: true, completion: nil)
}

但请注意,这可能会在未来的 iOS 版本中中断,因为这依赖于compact日期选择器呈现视图控制器的实现细节显示日历.如果您打印出所呈现的 VC 的类型,您将看到 _UIDatePickerIOSCompactViewController.领先的 _ 表明这是一个实现细节.

But note that this will potentially break in future iOS versions as this relies on the implementation detail that compact date pickers presents a view controller to show the calendar. If you print out the type of the presented VC, you'll see _UIDatePickerIOSCompactViewController. The leading _ suggests that this is an implementation detail.

关于 compact 的所有记录是:

All that is documented about compact is:

指示日期选择器显示为标签的样式,点击时会显示日历样式的编辑器.

所以在 iOS 的未来版本中,他们可以改为更改实现以不呈现新的视图控制器,这很可能会中断,然后您必须找到另一种方法.我现在没有看到任何记录在案的方法.

So in future versions of iOS, they could instead change the implementation to not present a new view controller, and this could very well break, and you'll have to find another way then. I see no documented way of doing this right now.

这篇关于当样式为 .compact 时,选择后关闭 UIDatePicker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 12:17