首页 > 解决方案 > 如何使按钮(或任何其他元素)在点击时显示 SwiftUI 的 DatePicker 弹出窗口?

问题描述

我正在尝试实现最简单的用例,但我无法弄清楚。我有一张日历的照片。我想要的只是在点击图片时显示 DatePicker 弹出窗口。我试图把它放在 ZStack 中,但这样做我无法隐藏默认数据文本字段:

ZStack {
    Image("icon-calendar")
    .zIndex(1)
    DatePicker("", selection: $date)
    .zIndex(2)
}

如何在没有荒谬的解决方法的情况下本地制作这个简单的布局?

标签: iosswiftswiftui

解决方案


我也有这个问题。几天睡不着想着解决办法。我用谷歌搜索了一百次,最后,我找到了实现这一目标的方法。现在是我所在时区的凌晨 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) {}
}

推荐阅读