我想迭代一個陣列ForEach,根據用例,它的子版本使用更少的元素。
ForEach(isExpanded ? $items : $items[..<4])
問題是如果我使用下標,我會收到錯誤訊息Result values in '? :' expression have mismatching types 'Binding<[RowItem]>' and 'Binding<[RowItem]>.SubSequence' (aka 'Slice<Binding<Array<RowItem>>>')。我不能這樣使用它,因為它不是陣列而是Slice. 只是投射到Array也不起作用。
uj5u.com熱心網友回復:
這是回應發布者第二個問題的示例代碼。
使用系結來存盤/傳遞/接收來自另一個結構的資料:
struct Test: View {
@State var bindWithChild: String = ""
var body: some View {
Text("\(bindWithChild)")
//when you edit data in the child view, it will updates back to the parent's variable
TestChild(receiveAndUpdate: $bindWithChild)
}
}
struct TestChild: View {
@Binding var receiveAndUpdate: String
var body: some View {
TextField("Enter here", text: $receiveAndUpdate)
}
}
但是,如果您的資料僅在一個結構中有效,并且您不需要在另一個結構中來回傳遞資料,請使用@State:
struct Test: View {
@State var binding: String = ""
var body: some View {
Text("\(binding)")
//when you edit data in the TextField below, it will update this Text too.
TextField("Enter data: ", text: $binding)
}
}
uj5u.com熱心網友回復:
您不必在陣列前面使用 $ 符號。
ForEach(isExpanded ? items[..<items.count] : items[..<4], id: \.self) { sub in
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/490184.html
上一篇:iOS中的字體字符高度變化
