如果@Published var更改,SwiftUI如何获取事件

时间:2020-05-22 07:58:20

标签: events triggers swiftui

我使用库RKmanager来显示带有dateRangePicker的日历。但是,如果参数rkManager.endDate从nil设置为一个日期,我将无法获得事件。

如果要设置范围,我想为dateRange激活和停用addButton。

如果发生更改,我的对象希望获取触发器

class RKManager : ObservableObject {
    @Published var startDate: Date! = nil
    @Published var endDate: Date! = nil

现在查看:

import SwiftUI

struct DateRangeView: View {

    @State var rkManager = RKManager(calendar: Calendar.current, minimumDate: Date(), maximumDate: Date().addingTimeInterval(60*60*24*365), mode: 1)

    @State private var addNewDateRangeIsDisabled: Bool = true


    var body: some View {
        VStack(alignment: .leading) {
            RKViewController(isPresented: .constant(false), rkManager: self.rkManager )


            Button(action: {
                if self.rkManager.endDate != nil
                    &&  self.rkManager.startDate != nil
                {
                    self.addNewDateRange()
                }
            }) {
                HStack {
                    Image(systemName: "plus.circle.fill")
                        .resizable()
                        .frame(width: 20, height: 20)
                    Text("Add new DateRange")
                }
            }
            .padding()

            .disabled(self.rkManager.endDate == nil) // --> here i want to change if the value changed
        }.navigationBarTitle("TestRoomName", displayMode: .inline)

    }

1 个答案:

答案 0 :(得分:1)

ObservableObject应该由ObservedObject动态属性包装器表示在视图中,以便在发布的属性更改时更新视图。

这是固定的

struct DateRangeView: View {

    @ObservedObject var rkManager = RKManager(calendar: Calendar.current, minimumDate: Date(), maximumDate: Date().addingTimeInterval(60*60*24*365), mode: 1)

   // ... other code