gpt4 book ai didi

ios - ButtonStyle 支持不同的形状

转载 作者:行者123 更新时间:2023-11-29 05:09:37 26 4
gpt4 key购买 nike

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

Function declares an opaque return type, but the return statements in its body do not have matching underlying types

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

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

最佳答案

这是可能的方法(编译和工作,使用 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))
}

}

关于ios - ButtonStyle 支持不同的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59807028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com