【问题标题】:Change text based on toggle values in SwiftUI根据 SwiftUI 中的切换值更改文本
【发布时间】:2019-07-02 04:34:51
【问题描述】:

我在 SwiftUI 中创建了一个带有文本、图像和导航按钮的视图。按下导航按钮时,它将导航到另一个包含 Toggle 的视图。当我更改 Toggle Value 时,我还想更改 Text 中的值以前的视图。

更改切换时值会更新,但在以前的视图中访问时未反映。

//BluetoothView.swift

struct BluetoothView: View {
    @ObjectBinding var bluetooth = Settings()

    var body: some View {
        return NavigationButton(destination: ToggleBluetoothView()) {
            HStack() {
                Image("default")
                    .resizable()
                    .cornerRadius(12)
                    .frame(width: 25, height: 25)
                    .clipped()
                    .aspectRatio(contentMode: .fit)
                Text("Bluetooth")
                    .color(.blue)
                    .font(.system(size: 18))
                Text(bluetooth.isBluetoothOn ? "On" : "Off")
                    .color(.gray)
                    .font(.subheadline)
                    .frame(width: 50, height: 40, alignment: .trailing)
            }
        }
    }
}

//ToggleBluetoothView.swift

struct ToggleBluetoothView: View {
    @ObjectBinding var bluetooth = Settings()

    var body: some View {
        Form {
            Section(header: Text("ENABLE TO CONNECT WITH NEARBY DEVICES")) {
                Toggle(isOn: $bluetooth.isBluetoothOn) {
                    Text("Bluetooth")
                    }
                }
            }
        }
    }

//Settings.swift

class Settings: BindableObject {

        var didChange = PassthroughSubject<Void, Never>()

       var isBluetoothOn = false { didSet { update() } }

        func update() {
            didChange.send(())
        }
    }

【问题讨论】:

    标签: ios text toggle swiftui swift5


    【解决方案1】:

    您在每个视图中分别实例化设置。两个视图都需要看到相同的设置对象:

    更改以下内容:

    NavigationButton(destination: ToggleBluetoothView(bluetooth: bluetooth)) { ... }
    

    并移除 ToggleBluetoothView 中的初始值:

    struct ToggleBluetoothView: View {
        @ObjectBinding var bluetooth: Settings
    
        var body: some View {
            Form {
                Section(header: Text("ENABLE TO CONNECT WITH NEARBY DEVICES")) {
                    Toggle(isOn: $bluetooth.isBluetoothOn) {
                        Text("Bluetooth")
                    }
                }
            }
        }
    }
    

    【讨论】:

    • 不客气。如果您要在多个视图中传递 @BindableObject,则可以考虑使用 @EnvironmentObject。检查 WWDC 会话 226(通过 SwiftUI 的数据流)。
    猜你喜欢
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2020-06-13
    • 2021-07-05
    • 1970-01-01
    相关资源
    最近更新 更多