【问题标题】:Supporting different Shapes in ButtonStyle支持 ButtonStyle 中的不同形状
【发布时间】:2020-01-19 03:54:38
【问题描述】:

我正在创建一个带有自定义 ButtonStyle 的 Button。我希望这种按钮样式支持两种不同的“外观”——圆形或圆角矩形。为此,我为外观案例定义了一个枚举,并将其传递给ButtonStyle,以便它可以根据需要修改其属性。我遇到了一个问题,那就是尝试为clipShape() 提供不同的Shapes。有一个编译时错误,我返回一些 Shape:

函数声明了一个不透明的返回类型,但返回语句在 它的主体没有匹配的底层类型

解决此错误并实现所需按钮外观的好方法是什么?

struct FloatingButton: View {
    enum FloatingButtonStyleType {
        case circle
        case roundedRectangle
    }

    private let image: Image
    private let style: FloatingButtonStyleType
    private let action: () -> ()

    var body: some View {
        Button(action: action) {
            image
        }
        .buttonStyle(FloatingButtonStyle(style: style))
    }

    init(image: Image, style: FloatingButtonStyleType, action: @escaping () -> ()) {
        self.image = image
        self.style = style
        self.action = action
    }
}

struct FloatingButtonStyle: ButtonStyle {
    let style: FloatingButton.FloatingButtonStyleType

    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .padding(.all, 10)
            .background(Color.black)
            .clipShape(clipShape())
    }

    private func clipShape() -> some Shape { //FIXME: Function declares an opaque return type, but the return statements in its body do not have matching underlying types
        switch style {
        case .circle:
            return Circle()
        case .roundedRectangle:
            return RoundedRectangle(cornerRadius: 5, style: .continuous)
        }
    }
}

【问题讨论】:

    标签: ios swift button swiftui


    【解决方案1】:

    这是可能的方法(编译和工作,使用 Xcode 11.2 / iOS 13.2 测试)

    struct FloatingButtonStyle: ButtonStyle {
        let style: FloatingButton.FloatingButtonStyleType
    
        struct StyleModifier : ViewModifier {
            let style: FloatingButton.FloatingButtonStyleType
    
            func body(content: Self.Content) -> AnyView {
                switch style {
                case .circle:
                    return AnyView(content.clipShape(Circle()))
                case .roundedRectangle:
                    return AnyView(content.clipShape(RoundedRectangle(cornerRadius: 5, 
                                   style: .continuous)))
                }
            }
        }
    
        func makeBody(configuration: Self.Configuration) -> some View {
            configuration.label
                .padding(.all, 10)
                .background(Color.black)
                .modifier(StyleModifier(style: style))
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多