Search code examples
iosswiftuiviewbackground-color

Setting background colour of view not working


I am trying to size the view programatically, so that it looks good on all device sizes, but I am having trouble getting started.

I have a view set out on the main.storyboard with horizontally and vertically centred constraints.

I have the following code in the viewDidLoad() method:

centerView.frame.size.width = 2/3 * view.frame.width

centerView.frame.size.height = 2/3 * view.frame.height

centerView.layer.backgroundColor = UIColor.blue.cgColor

The view does not have a background colour when I launch the app. What is the problem here?


Solution

  • You are mixing constraints with frames.. You can't do it like that.. Most likely, your view isn't sized correctly so you're not seeing the background colour even though it's there.. Check your view size in the view hierarchy inspector.

    Option 1: Keep mixing constraints with frames:

    func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    
        centerView.frame.size.width = 2.0/3.0 * view.frame.width
        centerView.frame.size.height = 2.0/3.0 * view.frame.height
        centerView.layer.backgroundColor = UIColor.blue.cgColor
    }
    

    This sets your view's frame after everything has been laid out. It must be done in viewDidLayoutSubviews or in layoutSubviews of a subclass.

    Option 2: Keep using only constraints

    func viewDidLoad() {
        super.viewDidLoad()
    
        centerView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 2.0 / 3.0, constant: 0.0).isActive = true
        centerView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 2.0 / 3.0, constant: 0.0).isActive = true
        centerView.layer.backgroundColor = UIColor.blue.cgColor
    }
    

    Option 3: Do it in the storyboard.. you can do a multiplier of 2.0 / 3.0 and set background colour there..