【发布时间】:2021-05-25 05:53:56
【问题描述】:
有没有办法将配置的视图提取到它自己的视图结构中,以便可以应用某些自定义?例如,我在 UI 的几个地方配置了 Button:
Button(action: {}) {
Text("Some Button Text")
.font(.custom("SomeFont", size: 17.0))
.fontWeight(.bold)
}
.frame(maxWidth: .infinity)
.frame(height: 50.0)
.foregroundColor(.black)
.background(Color("user-profile-action-call1"))
.clipShape(RoundedRectangle(cornerSize: CGSize(width: 10.0, height: 10.0)))
.padding([.leading, .trailing], 20.0)
.padding(.top, 33.0)
我希望能够重复使用它,指定不同的按钮文本和不同的背景颜色。显然,一种方法是创建一个新的View,它将String 和Color 作为参数/属性,并像这样使用它:
MyButton(title: "Some Button Text", color: Color("user-profile-action-call1"))
但这与 SwiftUI 不一致:
MyButton(title: "Some Button Text")
.background(Color("user-profile-action-call1"))
很遗憾,将背景放在.clipShape() 之后会导致填充区域而不是剪切区域。
有时我也想改变其他方面。但我不确定如何制作像这样的真正自定义视图。
【问题讨论】:
-
你可以像你提到的那样创建一个新视图或扩展 Button 或创建一个新的按钮样式,但我想这不是这里的问题,而是如何处理修饰符?
-
是的,为了与其他 SwiftUI 配置保持一致,能够以类似的方式应用修饰符会很好。