[英]Optional State or Binding in SwiftUI
我想問關於 SwiftUI 使用.onChange( value) { }
為什么如果我使用@State var some: SomeType?
使用可選類型,然后@Binding var some: SomeType
此運算符僅檢測更改,即從某個 SomeType 值更改為 nil ,反之亦然。 但是對基礎 object 值的更改不會被檢測為更改
前任。 @Binging var 進度:詮釋?
將進度從 nil 更改為 100 會檢測到更改,但如果我將值從 1 -> 2 -> 3 更改,則會跳過它們如果我使用@Binding var progress: Int
則有效
知道如何在 onChange() 中使用 Optionals 嗎?
這是可選的 State 和綁定的工作示例:
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) }
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.