我正在寻找一种方法来检测用户在选择日期时触摸 DatePicker 外部的情况,从而使日期选择器关闭。
@State private var date = Date()
@State private var isOpened = false
public init() {
self.date = Date()
self.isOpened = false
}
//ozadje barva
public var body: some View {
HStack() {
VStack(alignment: .leading, spacing: 0) {
Text("Start date")
Text(date.toString("dd-mm-yyy"))
}
Image(isOpened ? .icnClose : .icnCalendar)
.renderingMode(.template)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(
width: 24,
height: 24,
alignment: .center
)
}.overlay {
DatePicker(
"",
selection: $date,
displayedComponents: [.date])
.datePickerStyle(.compact)
.labelsHidden()
.blendMode(.destinationOver)
.onTapGesture(perform: {
print("tapped")
})
}
}
我需要它来改变视图的外观。我可以检测用户何时使用 tapGesture 再次单击 DatePicker 内部,但不能检测到用户在外部单击时。 有人有解决办法吗?
编辑1: 首选的解决方案是,以某种方式检测此组件的解除,因此我不必在放置此组件的视图上执行任何其他操作。
您可以简单地将
onTapGesture
放在最外部的容器上,如下所示:
VStack {
/// Your DatePicker and other Views here
}
/// Add these lines here
.frame(maxWidth: .infinity, maxHeight: .infinity)
/// Use this to make the View detect a tap, otherwise it will only work if the view has some solid color
.contentShape(.rect)
.onTapGesture {
print("Tap Outside")
}
让我知道这是否适合您!