我想澄清一下,我已经找到了答案,但是没有发现任何有用的信息。我已经发布了这个问题,但是由于我为代码提供了图像而不是文本,因此我对其进行了修改。
我有以下代码:
struct TimeChoiceView: View {
@State var buttonText = "None"
@State var isPressed = false
var text : String = "SomeView"
var body: some View{
VStack{
HStack{
VStack(alignment: .leading, spacing: 20){
Text(text).padding(EdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 0)).font(.system(size: 14))
}
Spacer()
VStack(alignment: .trailing){
Text(buttonText).padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 15)).foregroundColor(.gray).font(.system(size: 14)).onTapGesture {
self.isPressed = !self.isPressed
self.buttonText = self.buttonText == "None" ? "Undo" : "None"
}
}
}
HStack {
if isPressed {
TimeChoice()
}
}
}
}
}
在此视图中,TimeChoice
是使用以下代码实现的选择器:
struct TimeChoice: View{
@State var hours: Int = 8
@State var minutes: Int = 30
var body: some View {
HStack {
Spacer()
Picker("", selection: $hours){
ForEach(0..<23, id: \.self) { i in
Text("\(i)").tag(i)
}
}.pickerStyle(WheelPickerStyle()).frame(width: 50, height: 70).clipped()
Text(":")
Picker("", selection: $minutes){
ForEach(0..<60, id: \.self) { i in
Text(i < 10 ? "0\(i)" : "\(i)").tag(i)
}
}.pickerStyle(WheelPickerStyle()).frame(width: 50, height: 70).clipped()
Spacer()
}
}
}
选择器的出现是由onTapGesture
中的TimeChoiceView
方法触发的,但是如您所见,尝试再次按下Undo
按钮不会触发相关的动作。我可以设置选择器,但不能设置按钮。我有理由认为这与干扰选择器的.onTapGesture
方法有关,因为只有在我按下按钮并且选择器消失后才会发生这种情况。有没有人经历过这种行为?
问题是,在提供的代码中,Picker
在打开时与按钮重叠(甚至在视觉上被剪切,因此请处理所有轻敲事件。
解决方案是放置按钮面板上方(可选)显示选取器视图。经过Xcode 11.4 / iOS 13.4的测试]
var body: some View{
VStack{
HStack{
VStack(alignment: .leading, spacing: 20){
Text(text).padding(EdgeInsets(top: 0, leading: 15, bottom: 0, trailing: 0)).font(.system(size: 14))
}
Spacer()
VStack(alignment: .trailing){
Text(buttonText).padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 15)).foregroundColor(.gray).font(.system(size: 14))
.onTapGesture {
self.isPressed.toggle()
self.buttonText = self.buttonText == "None" ? "Undo" : "None"
}
}
}.zIndex(1) // << here !!
HStack {
if isPressed {
TimeChoice()
}
}
}
}