如何在 SwiftUI 中符合 ButtonStyle 协议?

Posted

技术标签:

【中文标题】如何在 SwiftUI 中符合 ButtonStyle 协议?【英文标题】:How to conform the ButtonStyle protocol in SwiftUI? 【发布时间】:2019-09-29 12:54:38 【问题描述】:

我想在 SwiftUI 中创建一个我想在整个应用程序中重复使用的自定义按钮。该按钮基本上只是一个可点击的图像,上面没有标签。 我考虑为它创建一个自定义 ButtonStyle。 不过,我在遵守 ButtonStyle 协议时遇到了问题,因为我不知道我应该在这里选择哪种类型。

我已经尝试过some View 或只是View 用于<#type>,但没有成功。

struct customButtonStyle: ButtonStyle 
    typealias Body = <#type>

尝试使用Viewsome View 时收到的错误消息是: Type 'customButtonStyle' does not conform to protocol 'ButtonStyle' 和 XCode 只是再次添加这一行 typealias Body = &lt;#type&gt;

非常感谢您的帮助。

【问题讨论】:

【参考方案1】:

您在makeBody 函数中定义自定义样式。您可以使用configuration.isPressed 在按下按钮时以稍微不同的方式配置按钮。

struct MyButtonStyle: ButtonStyle 

    func makeBody(configuration: Configuration) -> some View 
        configuration.label
            // all of the modifiers you want to apply in your custom style e.g.:
            .foregroundColor(configuration.isPressed ? .red : .blue)
    


【讨论】:

自定义 ButtonStyle 似乎不再适用于 ios 15。 ButtonStyle 直到现在仍然有效。此外,'func makeBody' 是遵守协议 'ButtonStyle' 的必要条件。

以上是关于如何在 SwiftUI 中符合 ButtonStyle 协议?的主要内容,如果未能解决你的问题,请参考以下文章