[英]Is it possible to edit a SwiftUI list element in the detail view?
我想在 SwiftUI 中 NavigationView 的詳細信息視圖中編輯列表元素的屬性。 如果我在同一視圖中編輯元素的屬性,列表會自動更新。 如果我打開列表元素的詳細視圖並編輯屬性,它會正確存儲在元素中並且也可以在主視圖中訪問,但列表不會更新。 這是代碼的一部分:
@ObservedObject var actions: ActionsList = ActionsList(l:[Action(dur: 1),Action(dur: 5), Action(dur: 10) ])
NavigationView{
List(actions.list, id: \.id ){ action in
NavigationLink(destination: ActionDetail(action:action)){
Timer_cell( action: action)
}
}
}
動作細節:
struct ActionDetail: View {
@State var action: Action
var body: some View {
Form {
HStack {
Text("Dauer")
Spacer()
TextField("Dauer", value: $action.duration, formatter: self.numberFormatter)
}
}
}
var numberFormatter : Formatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.generatesDecimalNumbers = true
return formatter
}()
}
動作列表:
import Foundation
class ActionsList: ObservableObject {
@Published var list :Array<Action> = [];
init(l : Array<Action>) {
list = l;
}
init(){
list = []
}
}
行動:
struct Action : Identifiable, Equatable, Hashable{
static func == (lhs: Action, rhs: Action) -> Bool {
lhs.duration == rhs.duration && lhs.type == rhs.type && lhs.id == rhs.id
}
var active: Bool
var duration: Int //in seconds
var type: ActionType
var id: UUID
init() {
active = true
duration = 10
type = ActionType.active
id = UUID()
}
init(dur: Int){
active = true
duration = dur
type = ActionType.active
id = UUID()
}
init(_id: UUID, _type: ActionType, dur: Int, _active: Bool){
id = _id
type = _type
duration = dur
active = _active
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(duration)
hasher.combine(type)
hasher.combine(active)
}
}
enum ActionType {
case pause, active, warmup, cooldown
}
首先,您必須將操作列表更改為環境變量,如下所示
@EnvironmentObject var actions: ActionsList
你可以從下面的代碼調用 ListView
let contentView = ActionListView().environmentObject(ActionsList(l:[Action(dur: 1),Action(dur: 5), Action(dur: 10) ]))
導航到詳細信息視圖時
NavigationView{
List(actions.list.indices){ index in
NavigationLink(destination: ActionDetail().environmentObject(self.actions.list[index])){
Timer_cell( action: self.$actions.list[index]) // this line does the trick
}
}
}
將您的 Action 模型struct
更改為Class
並符合Observable
協議
class Action : Identifiable, Equatable, Hashable, ObservableObject {
static func == (lhs: Action, rhs: Action) -> Bool {
lhs.duration == rhs.duration && lhs.type == rhs.type && lhs.id == rhs.id
}
var active: Bool
@Published var duration: Int
}
希望它會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.