Search code examples
iosswiftviewdidappearios-lifecycle

setup func can't change backgroundColor in a viewController


I actually use this to switch from a ViewController to another

    let vue = MAINSTORYBOARD.instantiateViewController(withIdentifier: "addhoraire") as! Addhoraire
    self.present(vue, animated: true, completion: nil)

sometimes I want to change something before show the view to user so in the VC with will be present I do a func. like that

// header and cercle.exemple are outlets of a UIView
    public func setup(selectedDay : String){
        loadViewIfNeeded()
        self.selectedDay = selectedDay
        print("jour selectionné : " + self.selectedDay)
        self.header.backgroundColor = UIColor.brown
        self.profTextField.backgroundColor = UIColor.yellow
        self.cercleExemple.backgroundColor = UIColor.yellow
    }

And when I want to switch now I do :

    let vue = MAINSTORYBOARD.instantiateViewController(withIdentifier: "addhoraire") as! Addhoraire
    vue.setup(selectedDay: selectedDayinHoraire)
    self.present(vue, animated: true, completion: nil)

So it will switch the new VC and execute setup like I want, ,textfield color is changed, cercleExemple too but header will not. view.backgroundColor, same problem ... but if I do in the same place header.isHidden = true it work. So it just refuse to change color

header and view bgcolor only change in ViewDidAppear. I don't understand why. It's been a week since I've been on this bug, it make me crazy ...


Solution

  • I found the issue, but I have no idea of the root cause. This seems like it might be an Apple bug. The issue is occurring because in Storyboard you are setting the header's background color using a color from the Assets.xcassets catalog (LightSideMenu). If instead of choosing a color from the Assets.xcassets you manually set the background color of the header using the RGB sliders or by entering the hex value #2A6D9E, then your header's background color will not be overridden. Also, make sure you are not resetting it elsewhere like in viewWillAppear or viewDidAppear as these will be called after your func setup(selectedDay : String) method.

    enter image description here