【发布时间】: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)
}
}
}
【问题讨论】: