【问题标题】:Custom Button in SwiftUI ListSwiftUI 列表中的自定义按钮
【发布时间】:2020-07-14 15:25:26
【问题描述】:

SwiftUI Custom Button in List

我正在尝试在 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()
    }
}

【问题讨论】:

    标签: swift list button swiftui


    【解决方案1】:

    在标准变体列表中拦截并处理点击检测的内容区域,在您的自定义样式中,默认情况下,它由不透明区域定义,在您的情况下仅是文本,因此更正的样式是

    使用 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)
      }
    }
    

    和用法,只是

    Button(action: {print("pressed")})
    {
        Text("Save")
    }.buttonStyle(BlueButtonStyle())
    

    甚至

    Button("Save") { print("pressed") }
        .buttonStyle(BlueButtonStyle())
    

    【讨论】:

    • listRowBackground() 将不再工作,在 iOS 15 上测试,有什么解决办法吗?我在Form 中使用它
    猜你喜欢
    • 2021-07-04
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 2017-05-02
    • 2020-05-15
    相关资源
    最近更新 更多