zak
zak

Reputation: 167

Using a variable from another class Swift

This is probably super simple and I am just missing something. I am trying to check if the view is loaded and visisble. Two edge cases, if it is visible, I just update a string inside the class, if it is not visable, I present the class. I tried to use .isViewLoaded on the class from another class and always got false returned. So I tried just have an initial value on the class that just gets updated is viewDidAppear gets called, but when accessing that value from another class I get no luck. Could anyone help here

class TimeController: UIViewController {

var openingTimeValue: String = ""
var timeShown: Bool = false

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
       return self.timeShown = true
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidAppear(animated)
    return self.timeShown = false
}

This is the class where I am setting the values and am trying to update when view is shown^

                if self.timeController.timeShown == true {
                self.timeController.openingTimeValue = timeUntilOpen
                return
            } else {
            DispatchQueue.main.async {
                _ = self.presentWeAreClosed(opensIn: timeUntilOpen)
            }

This is the class I always get false from. I originally tried to do this.

                if self.timeController.isViewLoaded

But still got false. I know it is something to do with inheritance which is what I'm still trying to get my head around in Swift. Thanks :)

Upvotes: 0

Views: 1327

Answers (1)

jnblanchard
jnblanchard

Reputation: 1200

At some point you'll need to declare a delegate on the TimeController then it can tell your class what the value is. We could do this inversely too, and have MyClass conform to a protocol that retrieves the value when needed.

protocol TimeReporter {
  func report(isShown: Bool)
}

class TimeController: UIViewController {

  var openingTimeValue: String = ""
  var timeShown: Bool = false {
    didSet(newValue) {
      delegate?.report(isShown: newValue)
    }
  }

  var delegate: TimeReporter?

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    timeShown = true
  }

  override func viewDidDisappear(_ animated: Bool) {
    super.viewDidAppear(animated)
    timeShown = false
  }

}

class MyClass: TimeReporter {

  var reported: Bool? 

  func setReporter() {
    guard let vc = UIApplication.shared.keyWindow?.rootViewController as? TimeController else { return }
    vc.delegate = self
  }

  func report(isShown: Bool) {
    reported = isShown

    // call your behavior here, or just store the new value.
    if (isShown) {
      self.timeController.openingTimeValue = timeUntilOpen
    } else {
      DispatchQueue.main.async {
        self.presentWeAreClosed(opensIn: timeUntilOpen)
      }
    }

  }

}

Upvotes: 1

Related Questions