0

I am trying to figure out how to update my xib labels when a button is pressed on another view controller

Currently I have a xib swift file that contains all my labels

var habit: Habit? {
    didSet {
        self.updateUI()
    }
}

func updateUI() {
    habitXibName?.text = habit?.title
    totalProgress?.text = habit?.totalCount
    progressBarXib?.progress = habit?.progress ?? 0.0
    userProgress?.text = String(habit?.userCount ?? 0)
}

In another view controller I have the following code

do {
        try realm.write {
            if selectedHabit!.userCount == (Int(selectedHabit!.totalCount )! - 1) {
                selectedHabit!.userCount += 1
                habitcell.habitXibName?.text = String(selectedHabit?.userCount ?? 0)
                view.addSubview(confettiView)
                confettiView.startConfetti()
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                    self.confettiView.stopConfetti()
                }
            } else {
                selectedHabit!.userCount += 1
            }
        }
    } catch {
        print(error)
    }

what I want to happen is to update my xib label to the selectedHabit?.userCount

habitcell.habitXibName?.text = String(selectedHabit?.userCount ?? 0)

However, my habitcell.habitXibName returns nil and I'm not sure why. Thanks for everything!

Alan Weng
  • 636
  • 6
  • 13
  • Is `habitXibName` an outlet? – aheze Jan 05 '21 at 20:50
  • yep! its a UIlabel – Alan Weng Jan 05 '21 at 20:52
  • Ok... how do you add `habitcell` as a subview? You might want to check [this](https://stackoverflow.com/a/29322364/14351818) – aheze Jan 05 '21 at 20:55
  • 2
    It habitCell being used in a tableView? How it being instantiated? What does this question have to do with Realm as there is no realm code within realm.write - maybe `selectedHabit` is a realm object? – Jay Jan 05 '21 at 21:12
  • Updating a view directly from an another view controller is rarely the right approach. You should have separation via your data model. When the model is updated then relevant views should react to that update. You can use `NotificationCenter` or Combine, for example. – Paulw11 Jan 05 '21 at 21:32

0 Answers0