ToolbarContent:添加一个 .disabled(Bool) 方法

ToolbarContent: add a .disabled(Bool) method

我为常用按钮创建了自定义 ToolbarContent,例如保存、编辑、取消等...

例如:


import SwiftUI

public struct SaveToolbarItem: ToolbarContent {
    private let placement: ToolbarItemPlacement
    private let action: () -> Void

    public init(placement: ToolbarItemPlacement = .confirmationAction,
                action: @escaping () -> Void = {}) {
        self.placement = placement
        self.action = action
    }

    public var body: some ToolbarContent {
        ToolbarItem(placement: placement) {
            Button(
                "Save"
            ) {
                action()
            }
        }
    }
}

通话现场:

        .toolbar {            
            SaveToolbarItem() {
                 // some code for the Action
                presentationMode.wrappedValue.dismiss()
            }
            .disabled(true) // Value of type 'SaveToolbarItem' has no member 'disabled'
        }

但是,我在尝试使用 isDisabled 方法时遇到以下错误:

Value of type 'SaveToolbarItem' has no member 'disabled'

如何减轻此错误?例如。也许只在我的自定义类型 ToolbarContent?

上定义 disabled

需要放在里面,喜欢

public var body: some ToolbarContent {
    ToolbarItem(placement: placement) {
        Button(
            "Save"
        ) {
            action()
        }
        .disabled(true)     // << here !!
    }
}

*当然要传入disabled的参数。

更新: 这是使用 built-in disabled 修饰符的可能方法。

测试 Xcode 13.2 / iOS 15.2

public struct SaveToolbarItem: ToolbarContent {
    private let placement: ToolbarItemPlacement
    private let action: () -> Void

    private var enabled = true

    public init(placement: ToolbarItemPlacement = .confirmationAction,
                action: @escaping () -> Void = {}) {
        self.placement = placement
        self.action = action
    }

    public var body: some ToolbarContent {
        ToolbarItem(placement: placement) {
            Button(
                "Save"
            ) {
                action()
            }
            .disabled(!enabled)
        }
    }

    func disabled(_ flag: Bool) -> Self {
        var newItem = self
        newItem.enabled = !flag
        return newItem
    }
}