从托管控制器重新加载SwiftUI视图

时间:2019-09-09 18:48:40

标签: ios watchkit swiftui

是否可以从其托管控制器重新加载swiftUI视图?

我有一个 WKHostingController ,其 body 带有swiftUI视图。当视图外部的通知被触发时,我需要更新视图。如果我尝试更改@Binding或@State变量,则会出错

  

我无法在视图外部更新值

但是我找不到刷新方法。

有什么想法吗?

托管控制器:

class WorkoutListInterfaceController : WKHostingController<WorkoutListView> {
  override var body: WorkoutListView {
    WorkoutListView(host: self)
  }


  override func didAppear() {
    // update WorkoutListView!!!
  }

  func showExercises(forWorkout workout: Workout) {
    WKInterfaceController.reloadRootControllers(withNamesAndContexts: [(name: "ExerciseListInterfaceController", context: workout as AnyObject)])
  }

  func showAddWorkout() {
    presentController(withNamesAndContexts: [("AddWorkoutHostingController", context: "" as AnyObject)])
  }
}

SwiftUI视图:

struct WorkoutListView : View {
  weak var host: WorkoutListInterfaceController?

  @State private var shouldPresentAddWorkout = false
  @State var workouts: [Workout] = Workout.all()

  init(host: WorkoutListInterfaceController) {
    self.host = host
  }

  var body: some View {
    return List {
      Section(header: Text("Workouts")
        .font(.system(size: 18))
        .fontWeight(.bold)
        .frame(height: 18))
      {
        ForEach(workouts) { workout in
          Button(action: {
            self.host?.showExercises(forWorkout: workout)
          }) {
            Text(workout.title)
          }
        }
      }

      Button(action: {
        self.host?.showAddWorkout()
      }) {
        Text("Add Workout")
          .fontWeight(.medium)
          .foregroundColor(.green)
          .frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
      }
    }
    .sheet(isPresented: $shouldPresentAddWorkout, onDismiss: {}) {
      AddWorkoutView(host: AddWorkoutHostingController())
    }
    .contextMenu {
      Button(action: { self.host?.showAddWorkout() },
             label: {
              VStack {
                Image(systemName: "plus")
                Text("Add Workout")
              }
      })
    }
  }
}

WorkoutListInterfaceController的{​​{1}}被调用,我想更新didAppear()

WorkoutListView上,不会调用swiftUI视图修饰符。我不知道这是错误还是预期的行为,这就是为什么我默认使用主机控制器上的onAppear()刷新视图的原因。

2 个答案:

答案 0 :(得分:0)

通过在显示的视图将被关闭时发布通知,使它可以与Combine和NotificationCenter一起使用:

NotificationCenter.default.post(name: .updateWorkoutsNotification, object: workouts)

然后在WorkoutListView视图模型中订阅该通知

答案 1 :(得分:0)