设计
Button
时,自定义ButtonStyle
只需要从环境变量中获取isEnabled
,如下所示。
自定义按钮样式
struct MyStyle: ButtonStyle {
@Environment(\.isEnabled) var isEnabled
func makeBody(configuration: Configuration) -> some View {
if isEnabled {
do enabled style
} else {
do disabled style
}
}
我为我的自定义控件创建了另一个样式原型,效果很好,但是
disabled(_:)
函数似乎没有为除Button
之外的任何东西设置isEnabled。
我需要根据“启用”状态调整控件的样式。
我试过在我的自定义控件中放置一个
Button
而不是使用 Image
和 gesture
然后使用自定义 ButtonStyle
,但是有点不可预测并且似乎只在控件中设置 Button
的样式而没有别的。然而,isEnabled
设置如预期。
我也尝试过使用
Button
,其中 Label
看起来像新控件,但我只希望 Button
在点击右侧而不是按钮上的任何地方时运行操作。我也很难限制Button
的可点击区域。
我想我可能会覆盖
disable(_:)
功能,但我不知道如何覆盖View
扩展的功能。
在使用我的新
Style
和新控件时,我可以在其上运行 disable(_:)
,它实际上禁用了我的 gesture
上的 Image
。但是没有设置isEnabled
的环境。
测试内置函数
struct ContentView: View {
var body: some View {
MyControl()
.controlStyle(MyControlStyle())
.disabled(true) <- Disables MyControl but does not set isEnabled
}
}
struct MyControlStyle: ControlStyle {
@Evironment(\.isEnable) var isEnabled <- Always true even if disabled is true
func makeBody(configuration: Configuration) -> some View {
if isEnabled {
do enabled style
} else {
do disabled style
}
}
尝试直接设置isEnabled
struct MyControl: View {
@State var disabled = false
func isDisabled(_ disabled: Bool) {
self.disabled = disabled
self.environment(\.isEnabled, !disabled)
}
var body: some View {
<Make View>
}
}
struct ContentView: View {
var body: some View {
MyControl()
.controlStyle(MyControlStyle())
.isDisabled(true)
}
}
struct MyControlStyle: ControlStyle {
@Evironment(\.isEnable) var isEnabled <- Always true even if disabled is true
func makeBody(configuration: Configuration) -> some View {
if isEnabled {
do enabled style
} else {
do disabled style
}
}
我还没有弄清楚需要做什么才能让
isEnabled
像我的自定义控件的按钮一样工作。