swift - 切换 swiftUI toggle() 时如何触发操作?
问题描述
在我的 SwiftUI 视图中,当 Toggle() 更改其状态时,我必须触发一个动作。切换本身只需要一个绑定。因此,我尝试在 @State 变量的 didSet 中触发操作。但是 didSet 永远不会被调用。
是否有任何(其他)方式来触发动作?或者有什么方法可以观察@State 变量的值变化?
我的代码如下所示:
struct PWSDetailView : View {
@ObjectBinding var station: PWS
@State var isDisplayed: Bool = false {
didSet {
if isDisplayed != station.isDisplayed {
PWSStore.shared.toggleIsDisplayed(station)
}
}
}
var body: some View {
VStack {
ZStack(alignment: .leading) {
Rectangle()
.frame(width: UIScreen.main.bounds.width, height: 50)
.foregroundColor(Color.lokalZeroBlue)
Text(station.displayName)
.font(.title)
.foregroundColor(Color.white)
.padding(.leading)
}
MapView(latitude: station.latitude, longitude: station.longitude, span: 0.05)
.frame(height: UIScreen.main.bounds.height / 3)
.padding(.top, -8)
Form {
Toggle(isOn: $isDisplayed)
{ Text("Wetterstation anzeigen") }
}
Spacer()
}.colorScheme(.dark)
}
}
期望的行为是当 Toggle() 更改其状态时触发操作“PWSStore.shared.toggleIsDisplayed(station)”。
解决方案
SwiftUI 2
如果您使用的是SwiftUI 2 / iOS 14,您可以使用onChange
:
struct ContentView: View {
@State private var isDisplayed = false
var body: some View {
Toggle("", isOn: $isDisplayed)
.onChange(of: isDisplayed) { value in
// action...
print(value)
}
}
}
推荐阅读
- css - 如何相对于其相对定位的父元素的内容框(不是填充框)对子元素进行绝对定位?
- java - 如何使用 Java 将字符串和整数写入 JSON 数组?
- javascript - 如何在每个循环中等待一个承诺?
- php - 如何在导入时跳过 .csv 中的第一行并在导出时添加一行?
- ruby-on-rails - 获取 Array 和 ActiveRecord 数千条记录之间的差异
- python-3.x - 如何将六边形 matplotlib 图转换为交互式散景图?
- webpack - 使用 Webpack 缩小 JS 文件
- mysql - 我可以在 mySQL 中添加带有条件的值吗
- ftp - 拉取大量文件 (10,000+) 时 sftp.mget 缓慢
- javascript - 通过代码主动触发 Health Bot 场景会引发错误