Pet*_*ber 10 list button swift swiftui
我正在尝试在 SwiftUI 列表中创建一个自定义按钮。我希望它有一个带有白色文本的蓝色背景,重要的是,在按下时保持蓝色并达到 50% 的不透明度,而不是默认的灰色。
我尝试使用自定义 ButtonStyle,但是当我这样做时,按钮的可点击区域减少到只有标签本身。如果我点击单元格的任何其他部分,颜色不会改变。如果我删除 ButtonStyle,则点击单元格上的任何位置都有效
我该如何解决这个问题,以便获得我的自定义颜色,包括点击时的颜色,但整个单元格仍然可以点击?
import SwiftUI
struct BlueButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.font(.headline)
.foregroundColor(configuration.isPressed ? Color.white.opacity(0.5) : Color.white)
.listRowBackground(configuration.isPressed ? Color.blue.opacity(0.5) : Color.blue)
}
}
struct ExampleView: View {
var body: some View {
NavigationView {
List {
Section {
Text("Info")
}
Section {
Button(action: {print("pressed")})
{
HStack {
Spacer()
Text("Save")
Spacer()
}
}.buttonStyle(BlueButtonStyle())
}
}
.listStyle(GroupedListStyle())
.environment(\.horizontalSizeClass, .regular)
.navigationBarTitle(Text("Title"))
}
}
}
struct ExampleView_Previews: PreviewProvider {
static var previews: some View {
ExampleView()
}
}
Run Code Online (Sandbox Code Playgroud)
Asp*_*eri 12
In standard variant List intercepts and handles content area of tap detection, in your custom style it is defined, by default, by opaque area, which is only text in your case, so corrected style is
Tested with Xcode 11.4 / iOS 13.4
struct BlueButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.font(.headline)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
.contentShape(Rectangle())
.foregroundColor(configuration.isPressed ? Color.white.opacity(0.5) : Color.white)
.listRowBackground(configuration.isPressed ? Color.blue.opacity(0.5) : Color.blue)
}
}
Run Code Online (Sandbox Code Playgroud)
and usage, just
Button(action: {print("pressed")})
{
Text("Save")
}.buttonStyle(BlueButtonStyle())
Run Code Online (Sandbox Code Playgroud)
and even
Button("Save") { print("pressed") }
.buttonStyle(BlueButtonStyle())
Run Code Online (Sandbox Code Playgroud)