我有一個SwiftUI
應用程式,它生成一個List
由保存在struct
.
我需要該行中的專案是可編輯的,所以我正在嘗試使用TextEditor
,但事實證明系結很困難。我有一個作業原型,但是TextEditor
s 是不可編輯的 - 我收到警告:
Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update.
這是我的代碼的一個大大縮短的版本,它產生了同樣的問題:
import SwiftUI
struct Item: Identifiable {
@State var stringValue: String
var id: UUID = UUID()
}
struct ArrayContainer {
var items: [Item] = [Item(stringValue: "one"), Item(stringValue: "two")]
}
struct ContentView: View {
@State var wrapperArray: ArrayContainer = ArrayContainer()
var body: some View {
List {
Section(header: Text("Test List")) {
ForEach (Array(wrapperArray.items.enumerated()), id: \.offset) { index, item in
TextEditor(text: item.$stringValue)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
如何將 TextEditor 系結到items
陣列中的項 stringValues?
TIA。
uj5u.com熱心網友回復:
@State
應該只用作您的屬性包裝器View
- 而不是您的模型。
您可以使用語法中的系結ForEach
來$
獲取專案的可編輯版本。
struct Item: Identifiable {
var stringValue: String
var id: UUID = UUID()
}
struct ArrayContainer {
var items: [Item] = [Item(stringValue: "one"), Item(stringValue: "two")]
}
struct ContentView: View {
@State var wrapperArray: ArrayContainer = ArrayContainer()
var body: some View {
List {
Section(header: Text("Test List")) {
ForEach ($wrapperArray.items, id: \.id) { $item in
TextEditor(text: $item.stringValue)
}
}
}
}
}
這可以進一步簡化以避免ArrayContainer
如果您愿意:
struct ContentView: View {
@State var items: [Item] = [Item(stringValue: "one"), Item(stringValue: "two")]
var body: some View {
List {
Section(header: Text("Test List")) {
ForEach ($items, id: \.id) { $item in
TextEditor(text: $item.stringValue)
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/505766.html