根据SwiftUI中的切换值更改文本

时间:2019-07-02 04:34:51

标签: ios text toggle swiftui swift5

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

更改切换开关时值会更新,但在上一个视图中访问时不会反映出来。

// 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(())
        }
    }

1 个答案:

答案 0 :(得分:0)

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

更改以下内容:

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")
                }
            }
        }
    }
}