要在 SwiftUI 中设置按钮样式,根据我的理解,您需要扩展 ButtonStyle
并实现 func makeBody(configuration: Self.Configuration) -> some View
,在其中您可以开始对 configuration.label
应用修改,它是对 Button
View 的引用。
现在,除了 label
字段之外,ButtonStyle.Configuration
还有一个用于 isPressed
的 bool 字段,但这似乎就是全部了。
如何检查按钮是否启用或禁用?
例如,我想在按钮周围绘制边框,如果启用按钮,我希望边框为蓝色,如果禁用,则边框为灰色。
我的第一个猜测是这样的:
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.overlay(
RoundedRectangle(cornerRadius: 4).stroke(configuration.isEnabled ? Color.blue : Color.gray, lineWidth: 1).padding(8)
)
}
但是没有 isEnabled
字段。
Apple 提供的 PlainButtonStyle
显然可以访问此信息,因为头文件中的文档注释声明它说“该样式可以应用视觉效果来指示按下、聚焦或按下”。按钮的启用状态。'
/// A `Button` style that does not style or decorate its content while idle.
///
/// The style may apply a visual effect to indicate the pressed, focused,
/// or enabled state of the button.
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public struct PlainButtonStyle : PrimitiveButtonStyle {
.....
有办法获取这些信息吗?
编辑:
在您建议关闭此问题之前,请阅读以下内容:
不久前也有人问过类似的问题。该问题没有指定任何上下文。
这里我有一个特定的上下文:创建通用的可重用按钮样式。
那里提供的答案还不够。我不能指望人们将禁用状态传递给样式构造函数。这样的重复工作太多了。
你能想象如果人们必须这样编写代码吗:
Button() { .... }.disabled(someExprssion).buttonStyle(MyCustomStyle(disabled: someExpression))
显然这是不可取的。
另外,很明显,Apple 提供的样式可以访问该信息,而不需要人们再次将禁用状态传递给该样式。
如果您关闭该问题,您将永远阻止任何人在 StackOverflow 上为此问题提供有用的答案。
在提议关闭之前请重新考虑。
编辑2:
我猜测,如果您可以获得 Button
View 的 EnvironmentValues.isEnabled
那么它可能是正确的值。
所以问这个问题的另一种方式是:在 SwiftUI 中是否有可能获取您没有自己定义的 View 的环境?
最佳答案
感谢这个博客,我找到了答案:https://swiftui-lab.com/custom-styling/
您可以通过创建包装 View 并在样式结构中使用它来从环境中获取启用状态:
struct MyButtonStyle: ButtonStyle {
func makeBody(configuration: ButtonStyle.Configuration) -> some View {
MyButton(configuration: configuration)
}
struct MyButton: View {
let configuration: ButtonStyle.Configuration
@Environment(\.isEnabled) private var isEnabled: Bool
var body: some View {
configuration.label.foregroundColor(isEnabled ? Color.green : Color.red)
}
}
}
此示例演示如何获取状态并使用它来更改按钮的外观。如果按钮被禁用,它将按钮文本颜色更改为红色;如果启用,则将按钮文本颜色更改为绿色。
关于ios - SwiftUI ButtonStyle - 如何检查按钮是否已禁用或启用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59169436/