Home > Software design >  UIView does not change colors after setting backgroundColor programmatically
UIView does not change colors after setting backgroundColor programmatically

Time:09-21

I'm creating a subview to add onto an existing view. I'm trying to assign the background color to this subview to red programmatically but displays as the defaulted color still.

let toggleView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))
        
toggleView.backgroundColor = UIColor.red

enter image description here

CodePudding user response:

As from the above code snippet it looks like that you are creating a view but not adding it as a subview to the parent view. It will be best if you can provide full function so that we can look into the actual cause.

CodePudding user response:

You have created the toggleView with a red background but you have not added it to the main view, this is what you should do:

let screenWidth = view.frame.size.width
let screenHeight = view.frame.size.height
    
let toggleView = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))
toggleView.backgroundColor = UIColor.red
view.addSubview(toggleView)
  • Related