swift - SwiftUI 中的可选状态或绑定
问题描述
我想在使用时询问有关 SwiftUI 行为的问题.onChange( value) { }
为什么如果我使用@State var some: SomeType?
可选类型,然后@Binding var some: SomeType
这个运算符只检测到更改,它就会从某个 SomeType 值更改为 nil,反之亦然。但是对基础对象值的更改不会被检测为更改
前任。@Binging var 进度:诠释?
将进度从 nil 更改为 100 会检测到更改,但是如果我将值从 1 -> 2 -> 3 更改,则会跳过它们如果我使用它就可以使用@Binding var progress: Int
知道如何将 Optionals 与 onChange() 一起使用吗?
解决方案
这是带有 State 和 Binding 的 optional 的工作示例:
import SwiftUI
struct ContentView: View {
@State private var progress: Int?
var body: some View {
CustomView(progress: $progress)
}
}
struct CustomView: View {
@Binding var progress: Int?
var body: some View {
Button("update") {
if let unwrappedInt = progress { progress = unwrappedInt + 1 }
else { progress = 0 } //<< █ █ Here: initializing! █ █
}
.onChange(of: progress) { newValue in
if let unwrappedInt = progress { print(unwrappedInt) }
}
}
}
推荐阅读
- c++ - C++:如何使#define 与自定义类一起工作?
- python - 从星期五开始创建一周
- jwt - Loopback 4 - 生成的令牌会过期多久?- 例如:待办事项
- x86 - 了解 Intel ME(管理引擎)初始化
- c# - 如果我可以简单地修复错误,为什么还要使用 try/catch?
- docker - 如何在 Kubernetes 中部署入口方法
- python - 如何使用光标对 API 进行分页?
- python - MessageBox 未在 Python GUI 中显示正确的输出
- php - WebDataRocks 枢轴顺序 Dinamclly
- javascript - React native:AsyncStorage 返回对象作为 React 子项和垃圾值无效