SwiftUI 基础之@EnvironmentObject 不被苹果公开认可的全局变量

SwiftUI 基础之@EnvironmentObject 不被苹果公开认可的全局变量

@EnvironmentObject 属性修饰器介绍

A dynamic view property that uses a bindable object supplied by an ancestor view to invalidate the current view whenever the bindable object changes.

中文翻译,that出现的位置将句子分为两段

一个动态视图属性,该属性为了无论任何时候可绑定对象发生改变时停用当前视图的属性。

大白话:@EnvironmentObject 修饰的变量权限最高,即使你取同样的名字也不能比我的权限高,在所有@EnvironmentObject的地方,只有我一个。其实就是全局变量。

代码

下面的代码请参考下面代码看看,仔细对比不同之处:

  • SwiftUI 基础之Toggle控件与@Binding属性装饰器(含代码demo)
import SwiftUI

struct Product : Identifiable{
    let id = UUID()
    let title:String
    let isFavorited:Bool
}
struct FilterView: View {
    //@Binding var showFavorited: Bool
     @EnvironmentObject var musicState : MusicPlayerState

    var body: some View {
        Toggle(isOn: $musicState.isPlaying) {
            Text("Change filter")
        }
    }
}

struct ContentView: View {
    
    let products: [Product] = [
        Product(title:"abc1",isFavorited: true),
        Product(title:"abc2",isFavorited: true),
        Product(title:"abc3 false",isFavorited: false),
        Product(title:"abc4",isFavorited: true),
        
    ]
    
   // @State private var showFavorited: Bool = false
    @EnvironmentObject var musicState : MusicPlayerState
    
    var body: some View {
        List {
           FilterView()
            
            ForEach(products) { product in
                if !self.musicState.isPlaying || product.isFavorited {
                    Text(product.title)
                }
            }
        }
    }
    
    
}

另外为何了项目,运行请在SceneDelegate.swift中添加下面代码

import UIKit
import SwiftUI

class MusicPlayerState: ObservableObject {
    @Published var isPlaying: Bool = false
}

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView()
        let musicState = MusicPlayerState()
        
        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView.environmentObject(musicState))
            self.window = window
            window.makeKeyAndVisible()
        }
    }

更多SwiftUI教程和代码关注专栏

  • 请关注我的专栏 SwiftUI教程与源码

你可能感兴趣的:(SwiftUI 基础之@EnvironmentObject 不被苹果公开认可的全局变量)