当我使用SwiftUI时,我想问一个关于.onChange( value) { }
行为的问题
为什么如果我使用带有可选类型的@State var some: SomeType?
,然后使用@Binding var some: SomeType
,这个操作符只检测到更改,它会从某个SomeType值更改为零,反之亦然。但是,对基础对象值的更改不会被检测为更改。
例如。@Binging进步: Int?
将进度从零更改为100将检测到变化,但如果我从1 -> 2 -> 3中更改值,则跳过它们,如果使用@Binding var progress: Int
则有效。
知道如何在onChange()中使用选项词吗?
发布于 2021-04-02 01:21:59
下面是带有状态和约束力的可选示例:
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) }
}
}
}
https://stackoverflow.com/questions/66916454
复制