Search code examples
iosswiftalphauicolor

Add alpha to view VS Add alpha to UIColor


Is writing this :

view.backgroundColor = UIColor.white.withAlphaComponent(0.9)

Equivalent to this:

view.backgroundColor = UIColor.white
view.alpha = 0.9

if not, what is the difference ?


Solution

  • Simple explanation

    Case 1:

    viewMain.backgroundColor = UIColor.white.withAlphaComponent(0.9)
    

    it will reduce the alpha color of the particular view i.e. viewMain here.

    Case 2:

    viewMain.alpha = 0.5
    

    It will reduce the opacity of the view and if viewMain have multiple views then all views alpha will be reduced that amount.

    Example :

    Let be your view hierarchy is like this

    viewMain
         -> view1
             -> view2
    

    Now from Case1, alpha of ViewMain will be reduced only. But in Case 2 alpha of viewMain, view1, view2 will be reduced.

    If you have no hierarchy, then both are same.

    enter image description here

    If you have view hierarchy, then it makes effect like below

    enter image description here