2024-01-09|閱讀時間 ‧ 約 26 分鐘

SwiftUI-Preview帶有Binding參數的View

在寫SwiftUI view的時候,碰到一個瓶頸(? 帶有Binding的參數要如何preview。
舉例來說有個右邊圖片左邊文字的View,給他一個@Binding var isActive: Bool的狀態,當active時圖片要跟著改變:

struct RightImageView: View {
@State var activeIcon: String
@State var originalIcon: String
@State var title: String
@Binding var isActive: Bool
var body: some View {
HStack {
Image(systemName: isActive ? activeIcon : originalIcon)
Text(title)
}.font(.system(size: 14.0))
.frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
.padding([.all], 10.0)
.background(Color.blue)
}
}

isActive = false



isActive = true


單獨Preview時,Binding參數要怎麼填??????

出現錯誤


Xcode14我是做一個@State private參數填進preview裡

struct RightImageView_Previews: PreviewProvider {
@State private static var isActive = false
static var previews: some View {
RightImageView(activeIcon: "arrow.up", originalIcon: "arrow.down", title: "456", isActive: $isActive)
}
}


Xcode15 preview的預設變成macro

沒辦法再寫@State private var🫨

#Preview {
// your view​
}


後來查到一個比較好的作法

StatefulPreviewWrapper

struct StatefulPreviewWrapper<Value, Content: View>: View {
@State var value: Value
var content: (Binding<Value>) -> Content
var body: some View {
content($value)
}
init(_ value: Value, content: @escaping (Binding<Value>) -> Content) {
self._value = State(wrappedValue: value)
self.content = content
}
}


用法

#Preview {
StatefulPreviewWrapper(false) { isActive in
RightImageView(activeIcon: "arrow.up", originalIcon: "arrow.down", title: "456", isActive: isActive)
}
}


不過只能塞一個Binding參數,如果有好幾個要在自己擴寫


參考資料:

https://developer.apple.com/forums/thread/118589



分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.