这更多是一个概念验证,但这可能是一种方式:
import SwiftUI
struct ContentView: View {
@State private var showPicker = true
@State var selectedDate = Date()
Button {
withAnimation {
showPicker.toggle()
}
} label: {
Text(Text(selectedDate.getFormattedDate(format:"HH:mm:")))
.padding()
.padding(.horizontal)
.background(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.gray)
)
}
.background(
DatePicker("", selection: $selectedDate, displayedComponents: .hourAndMinute)
.datePickerStyle(.wheel)
.frame(width: 200, height: 100)
.clipped()
.background(Color.gray.cornerRadius(10))
.opacity(showPicker ? 1 : 0 )
.offset(x: 50, y: 90)
).onChange(of: selectedDate) { newValue in
withAnimation {
showPicker.toggle()
}
}
}
DatePicker
视图的不透明度设置为0.011
(这是我找到的最小不透明度值,可以很好地隐藏它并保持其功能),然后使用.overlay
将其放在你定制的视图上面,下面是一个示例:struct MyDatePicker: View {
@State private var selectedDate = Date()
var body: some View {
// Put your own design here
HStack(spacing: 2) {
Text(selectedDate.formatted(.dateTime.day().month().year()))
.font(.system(size: 13, weight: .semibold))
Image(systemName: "chevron.right")
.font(.system(size: 9, weight: .bold))
}
.padding(8)
.foregroundColor(.white)
.background(RoundedRectangle(cornerRadius: 15, style: .continuous).foregroundColor(.blue))
// Put the actual DataPicker here with overlay
.overlay {
DatePicker(selection: $selectedDate, displayedComponents: .date) {}
.labelsHidden()
.contentShape(Rectangle())
.opacity(0.011) // <<< here
}
}
}
zindex
,但似乎已经有一个可行的解决方案了。唯一不太好的地方是用户必须再次点击按钮才能隐藏DatePicker
;你看到任何可能让他们点击任何地方来隐藏它的可能性吗? - swalkner.onChange()
,这样会很烦人,而是使用.onTapGesture()
,这样你仍然可以滑动选择器,但在点击时会隐藏选择器。 - undefined