我正在尝试创建我自己的 Button 版本,方法是将其包装在视图中,从而打开添加更多功能/隐藏样式修饰符的能力。我知道这不会带来好处,而且 ButtonStyles 很强大。但是为了超级干净的代码,我很好奇它是如何实现的。
在最精简的形式中,我想写一些类似的东西(基于 Button 自己的签名):
struct MyCustomButton: View {
let action : () -> Void
let contents : () -> PrimitiveButtonStyleConfiguration.Label
var body : some View {
Button(action: self.action) {
self.contents()
}
}
}
Run Code Online (Sandbox Code Playgroud)
然而,当我尝试使用它时......
struct MyView : View {
var body : some View {
MyCustomButton(action: { doSomething() }) {
Text("My custom button")
}
}
}
Run Code Online (Sandbox Code Playgroud)
...我收到以下编译错误:无法将“文本”类型的值转换为关闭结果类型“PrimitiveButtonStyleConfiguration.Label”
已经想通了:
struct NewButton<Content: View> : View {
let content : ()-> Content
let action: () -> Void
init(@ViewBuilder content: @escaping () -> Content, action: @escaping () -> Void) {
self.content = content
self.action = action
}
var body: some View {
Button(action: self.action) {
content()
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1117 次 |
| 最近记录: |