【问题标题】:Rectangle overlay on hovering a custom button悬停自定义按钮时的矩形叠加
【发布时间】:2020-05-07 09:39:23
【问题描述】:

我正在尝试定义一个自定义按钮样式,悬停时会在该按钮周围弹出一个矩形。

struct CustomButtonStyle: ButtonStyle {
@State private var isOverButton = false

func makeBody(configuration: Self.Configuration) -> some View {

    ZStack {
        configuration.label
            .frame(minWidth: 0, maxWidth: .infinity)
            .padding()
            .foregroundColor(.white)
            .background(Color("Frost1"))
    }
    .padding(3)
    .onHover { over in
        self.isOverButton = over
        print("isOverButton:", self.isOverButton, "over:", over)
    }
    .overlay(VStack {
        if self.isOverButton {
            Rectangle()
                .stroke(Color("Frost1"), lineWidth: 2)
        } else {
            EmptyView()
        }
    })
}}

打印行显示设置变量“isOverButton”不起作用。我应该使用哪种类型的变量状态,可以从“onHover”更新并更新“overlay”?

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    这里有一个解决方案。使用 Xcode 11.4 测试。

    struct TestOnHoverButton: View {
        var body: some View {
            Button("Button") {}
                .buttonStyle(CustomButtonStyle())
        }
    }
    
    struct CustomButtonStyle: ButtonStyle {
    
        private struct CustomButtonStyleView<V: View>: View {
            @State private var isOverButton = false
    
            let content: () -> V
    
            var body: some View {
                ZStack {
                    content()
                        .frame(minWidth: 0, maxWidth: .infinity)
                        .padding()
                        .foregroundColor(.white)
                        .background(Color.blue)
                }
                .padding(3)
                .onHover { over in
                    self.isOverButton = over
                    print("isOverButton:", self.isOverButton, "over:", over)
                }
                .overlay(VStack {
                    if self.isOverButton {
                        Rectangle()
                            .stroke(Color.blue, lineWidth: 2)
                    } else {
                        EmptyView()
                    }
                })
            }
        }
    
        func makeBody(configuration: Self.Configuration) -> some View {
            CustomButtonStyleView { configuration.label }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-22
      • 2011-09-01
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-14
      • 2013-04-15
      • 2015-11-02
      相关资源
      最近更新 更多