ericathanas
ericathanas

Reputation: 223

Set a bool value using model object didSet

I'm struggling to figure out how to properly set bool values using a model object's didSet. My app has a series of swipable cards where some flip and some don't. This code below is the CardView which is run for each card created.

Currently, the code works perfectly for the image and label—each card loads unique information based each card's model object. However, the button and isFlippable property are where I'm struggling.

The code right now is always loading the green pathway. The weird thing, however, is that even when the cardModel should sets the button isEnabled to false, it will still load the green (but the button won't work, so it did become disabled...)

var cardModel: CardModel! {
   didSet {
      imageView.image = cardModel.image
      label.text = cardModel.label
      flipButton.isEnabled = cardModel.isFlippable
      isBackShowing = cardModel.isFlippable //Intentionally use isFlippable here because I want the initial layout to be based on this true or false value.
   }
}


let imageView = UIImageView()
let label = UILabel()
let flipButton = UIButton()
var isBackShowing = false

override init(frame: CGRect) {
    super.init(frame: frame)
    setupLayout()
}

fileprivate func setupLayout() {

    if flipButton.isEnabled == true {
        if isBackShowing == true {
            backgroundColor = .red
        } else {
            backgroundColor = .green
        }
    } else {
        backgroundColor = .yellow
    }
}

I also have code for when the button flips that alternates "isBackShowing" and then calls setupLayout()—it is working fine. But it always loads as false during the initial setup of the card.

Upvotes: 2

Views: 797

Answers (1)

Roman Tsymbaliuk
Roman Tsymbaliuk

Reputation: 311

For better readability you can little bit update your code replacing var isBackShowing = Bool() by var isBackShowing = false.

And also you can call setupLayout() to update your layout after setting of cardModel. For example didSet of cardModel can looks like this:

var cardModel: CardModel! {
   didSet {
      imageView.image = cardModel.image
      label.text = cardModel.label
      flipButton.isEnabled = cardModel.isFlippable
      isBackShowing = cardModel.isFlippable
      setupLayout()
   }
}

Upvotes: 1

Related Questions