首页 > 解决方案 > 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() 一起使用吗?

标签: swiftswiftui

解决方案


这是带有 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) }
            
        }

    }
}

推荐阅读