ios - 根据 SwiftUI 中的切换值更改文本
问题描述
我在 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(())
}
}
解决方案
您在每个视图中分别实例化设置。两个视图都需要看到相同的 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")
}
}
}
}
}
推荐阅读
- node.js - 在 aws elastic beanstalk 中启动节点 pm2 进程管理器的问题,npm 更新检查失败
- maven - Hudson Locks and Latches jenkins 插件构建失败
- sql - 查询不排除具有一定权限的人
- laravel - Laravel 模型组默认
- excel - 无法在 Excel 中获得索引匹配
- azure-logic-apps - 在 LogicApp 中更新 Json 数组
- python - 如何使用 python libtorrent DHT 播种?
- xamarin - 如何使用 https://www.youtube.com/get_video_info?video_id={VideoId} 从 youtube 中提取 url
- python - 按钮按下创建/替换新窗口
- go - 在 Go 中使用包含 int 和 str 的数组