【问题标题】:How to conform the ButtonStyle protocol in SwiftUI?如何在 SwiftUI 中符合 ButtonStyle 协议?
【发布时间】: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;

非常感谢您的帮助。

【问题讨论】:

    标签: ios swift swiftui


    【解决方案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' 的必要条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多