ios - 如何使按钮(或任何其他元素)在点击时显示 SwiftUI 的 DatePicker 弹出窗口?
问题描述
我正在尝试实现最简单的用例,但我无法弄清楚。我有一张日历的照片。我想要的只是在点击图片时显示 DatePicker 弹出窗口。我试图把它放在 ZStack 中,但这样做我无法隐藏默认数据文本字段:
ZStack {
Image("icon-calendar")
.zIndex(1)
DatePicker("", selection: $date)
.zIndex(2)
}
如何在没有荒谬的解决方法的情况下本地制作这个简单的布局?
解决方案
我也有这个问题。几天睡不着想着解决办法。我用谷歌搜索了一百次,最后,我找到了实现这一目标的方法。现在是我所在时区的凌晨 1:50,我现在可以愉快地睡觉了。信贷去追逐在这里的答案
此处演示:https ://media.giphy.com/media/2ILs7PZbdriaTsxU0s/giphy.gif
神奇的代码
struct ContentView: View {
@State var date = Date()
var body: some View {
ZStack {
DatePicker("label", selection: $date, displayedComponents: [.date])
.datePickerStyle(CompactDatePickerStyle())
.labelsHidden()
Image(systemName: "calendar")
.resizable()
.frame(width: 32, height: 32, alignment: .center)
.userInteractionDisabled()
}
}
}
struct NoHitTesting: ViewModifier {
func body(content: Content) -> some View {
SwiftUIWrapper { content }.allowsHitTesting(false)
}
}
extension View {
func userInteractionDisabled() -> some View {
self.modifier(NoHitTesting())
}
}
struct SwiftUIWrapper<T: View>: UIViewControllerRepresentable {
let content: () -> T
func makeUIViewController(context: Context) -> UIHostingController<T> {
UIHostingController(rootView: content())
}
func updateUIViewController(_ uiViewController: UIHostingController<T>, context: Context) {}
}
推荐阅读
- python - 从 timedelta64 转换为 float 时得到 NaN
- reactjs - React material-ui datagrid 编辑问题
- python - 在 Jupyter Notebook 中读取 CSV URL
- c# - Linq 过滤器生成器不接受用于过滤器类型 IN 的 lambda
- google-apps-script - 我想在谷歌表上更改此脚本
- hash - SHAKE256询价
- c# - 我的 Azure 应用配置终结点有什么问题?
- javascript - 使用 Javascript Selenium Python 从验证码下载音频文件
- spring-webflux - Spring R2dbc:有没有办法从 postgresql 数据库中获取恒定流并处理它们?
- java - 返回类型方法“从不使用方法的返回值”问题