【问题标题】:Background appears to be above button in SwiftUI. Am I doing it wrong背景似乎在 SwiftUI 中的按钮上方。我做错了吗
【发布时间】:2019-11-28 02:30:00
【问题描述】:

我正在使用 SwiftUI 慢慢构建一个应用程序,该应用程序使用 Sections 对自定义视图进行分组。自定义控件有按钮。在我为这些部分添加背景之前,一切都按我的预期工作。

在尝试调试附加到按钮的代码后,我转储了视图层次结构,在那里我可以看到按钮似乎被背景覆盖了。

import SwiftUI

struct ContentView : View {
    var body: some View {
        VStack {
            Section(header: Text("Two rows")) {
                Row()
                Row()
            }
        }
        .padding(.all, 12)
        //.background(Color.gray, cornerRadius: 5)
        .border(Color.black, width: 1, cornerRadius: 5)
    }
}

struct Row: View {
    @State var item = "0"

    var body: some View {
        HStack {
            Button(
                action: { self.item += "+" },
                label: { Image(systemName: "plus.circle") }
            )
            Text(item)
            Button(
                action: { self.item += "-" },
                label: { Image(systemName: "minus.circle") }
            )
        }

    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View { ContentView() }
}
#endif

显示的代码并没有做太多,按钮只是将 + 或 - 附加到 0。当 .background() 行未注释但按钮不起作用时。

看起来部分是视图的元组,边框和背景应用于所有视图而不是组,这就是我添加最外层 vstack 的原因

【问题讨论】:

  • 使用Image(systemName: "minus.circle").tapAction { self.item += "-" } 代替Button 似乎效果很好。点击Button 标签实际上也可以。你只需要非常精确。
  • 虽然并非总是如此,但效果很好,我认为您必须点击图像的黑暗部分才能使其工作。我仍然想知道为什么背景似乎在按钮上方。

标签: button background swiftui sections


【解决方案1】:

可能重复:SwiftUI: Custom button does not recognize touch with clear background and buttonStyle

添加.contentShape(Rectangle()) 也应该适用于这种情况。

【讨论】:

    【解决方案2】:

    我不太确定为什么会这样,但是当您添加背景时,按钮上的点击框似乎基本上消失了。我假设这是一个错误,但也许其他人可以解释为什么会发生这种情况。

    至于问题的解决方案,我通过在按钮内的图像上设置框架来让您的代码工作。

    HStack {
        Button(action: { self.item += "+" }) {
            Image(systemName: "plus.circle")
                .frame(width: 20, height: 20)
        }
        Text(item)
        Button(action: { self.item += "-" }) {
            Image(systemName: "minus.circle")
                .frame(width: 20, height: 20)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多