How to set custom highlighted state of SwiftUI Button

sub*_*dan 11 swiftui

I have a Button. I want to set custom background color for highlighted state. How can I do it in SwiftUI?

在此处输入图片说明

Button(action: signIn) {
    Text("Sign In")
}
.padding(.all)
.background(Color.red)
.cornerRadius(16)
.foregroundColor(.white)
.font(Font.body.bold())
Run Code Online (Sandbox Code Playgroud)

ars*_*ius 35

已针对SwiftUI beta 5更新

SwiftUI实际上为此提供了一个APIButtonStyle

struct MyButtonStyle: ButtonStyle {

  func makeBody(configuration: Self.Configuration) -> some View {
    configuration.label
      .padding()
      .foregroundColor(.white)
      .background(configuration.isPressed ? Color.red : Color.blue)
      .cornerRadius(8.0)
  }

}


// To use it
Button(action: {}) {
  Text("Hello World")
}
.buttonStyle(MyButtonStyle())

Run Code Online (Sandbox Code Playgroud)

  • 这仅适用于未选择的按下状态,这只是一个瞬时状态:“指示用户当前是否按下按钮的布尔值。” https://developer.apple.com/documentation/swiftui/buttonstyleconfiguration/ispressed (3认同)

Blu*_*pud 6

据我所知,目前尚无官方支持的方法。您可以使用以下解决方法。这产生了与UIKit中相同的行为,在UIKit中,点击按钮并将手指从其上拖动将使按钮保持突出显示状态。

struct HoverButton<Label>: View where Label: View {

    private let action: () -> ()

    private let label: () -> Label

    init(action: @escaping () -> (), label: @escaping () -> Label) {
        self.action = action
        self.label = label
    }

    @State private var pressed: Bool = false

    var body: some View {
        Button(action: action) {
            label()
                .foregroundColor(pressed ? .red : .blue)
                .gesture(DragGesture(minimumDistance: 0.0)
                    .onChanged { _ in self.pressed = true }
                    .onEnded { _ in self.pressed = false })
        }    
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 好发现!也可以使用`.longPressAction(minimumDuration:0,maximumDistance:.infinity,{}){按下self.pressed =按下}}来完成。 (4认同)

小智 5

我正在寻找类似的功能,我是通过以下方式做到的。

我创建了一个特殊的 View 结构,以我需要的样式返回一个 Button,在这个结构中,我添加了一个选中的 State 属性。我有一个名为“table”的变量,它是一个 Int,因为我的按钮是一个带有数字的圆形按钮

struct TableButton: View {
    @State private var selected = false

    var table: Int

    var body: some View {
        Button("\(table)") {
            self.selected.toggle()
        }
        .frame(width: 50, height: 50)
        .background(selected ? Color.blue : Color.red)
        .foregroundColor(.white)
        .clipShape(Circle())
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我在我的内容中使用查看代码

HStack(spacing: 10) {
  ForEach((1...6), id: \.self) { table in
    TableButton(table: table)
  }
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个带有 6 个按钮的水平堆栈,选择时颜色为蓝色,取消选择时为红色。

我不是一个有经验的开发人员,只是尝试了所有可能的方法,直到我发现这对我有用,希望它对其他人也有用。