swa*_*ner 5 datepicker swiftui
我需要一个自定义“标签”,其行为是在某种弹出窗口中打开日期选择器,即使在 iPhone 上也是如此。
当我使用紧凑格式的内置 DatePicker 时,我有在弹出窗口中打开轮子的行为,但我无法自定义具有灰色背景的“折叠”版本的外观(事实上,我可以将其更改为其他一些颜色,但不是白色,例如,它根本不起作用)。
另一种选择是将自定义Text包裹在 a 内Button,然后打开 DatePicker,但我不知道如何在 iPhone 上实现弹出框效果。所以我想第一个选项会更容易,但是如何为紧凑的日期选择器实现自定义布局?没有什么超级花哨的,只是这样的:
而不是这样的东西
这有点hacky,但另一种方法是将实际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
}
}
}
Run Code Online (Sandbox Code Playgroud)
它更多的是概念证明,但这可能是一种方式:
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()
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,DidSet 或 willSet 对于对象来说是不可能的,但是,我们有一个很好的解决方法onChange。当日期改变时,只需切换即可。
| 归档时间: |
|
| 查看次数: |
5821 次 |
| 最近记录: |