SwiftUI有时不更新@EnvironmentObject

时间:2020-10-06 15:37:38

标签: swift swiftui

在此示例中,我尝试将状态保存在@EnvironmentObject中并将其传递给DepthButtonView,但是我的问题是有时它会丢失settings.tradeChartType中的DepthButtonView更新。是bug还是我做错了什么?

P.S。 我知道@State属性,只是我需要在项目中进行这种设置

任何建议将不胜感激

struct BodyView: View {
    
    var hideAction: () -> Void
    var fullScreenAction: () -> Void
    var chartTypeAction: (TradeChartView.ChartType) -> Void
    
    @EnvironmentObject var settings: AppSettings
    
    var body: some View {
        Group {
            Button(action: {
                
                if settings.tradeChartType == .trading {
                    settings.tradeChartType = .depth
                    
                } else {
                    settings.tradeChartType = .trading
                    
                }
                
                chartTypeAction(settings.tradeChartType)
            }, label: {
                DepthButtonView(tradeChartType: $settings.tradeChartType)
            })
            Spacer()
            Button(action: {
                fullScreenAction()
            }, label: {
                Image("HeaderTradeChartZoom")
            })
            if !settings.tradeChertFullScreen {
                Button(action: {
                    hideAction()
                }, label: {
                    Image("HeaderTradeChartHide")
                })
            }
        }
    }
    struct DepthButtonView: View {
        @Binding var tradeChartType: TradeChartView.ChartType
        
        var body: some View {
            Group {
                Text(LocalString(tradeChartType == .trading ? "cis.retail.ios.header.depth.button" : "cis.retail.ios.header.trading.button"))
                    .customFont(name: .ubuntuMedium, size: 16)
                    .foregroundColor(Color.primaryBlue).fixedSize()
                Image("HeaderLeftBlueArrow")
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我看不到在这里拥有Binding的原因,因此请尝试直接使用,例如

DepthButtonView(tradeChartType: settings.tradeChartType)

struct DepthButtonView: View {
    var tradeChartType: TradeChartView.ChartType
    
    var body: some View {
        // .. other code

注意:我假设tradeChartType中的@PublishedAppSettings