3

I have code under viewDidLayoutSubviews with intention of making an image transparent (alpha = 0) in the beginning which slowly fades in (into alpha = 1) with code under viewDidAppear. Also, I have a button which changes it's own label text when pressed.

However, when the button is pressed and the label changes, the image (which I've specified under viewDidLayoutSubviews) also disappears. Which I think is because the code under viewDidLayoutSubviews has been called?

My question is:

1) What is the meaning of viewDidLayoutSubviews? Why is it called when the button label changes? Just briefly/generally, what is setNeedsLayout & setNeedsDisplayInRect?

2) Is it better to use viewWillAppear then?

Here are 2 similar questions but I couldn't understand enough from them:

1) viewDidLayoutSubviews is called when label changes (xcode) (swift)

2) Why viewdidlayoutsubviews call multiple times?

Community
  • 1
  • 1
Allister Bah
  • 1,134
  • 3
  • 13
  • 19

2 Answers2

9

As name suggests, viewDidLayoutSubviews is called when the view of your viewController has just finished its laying out and you can assume that at that point your views are in their correct places/frames according to your autolayout constraints. You shouldn't perform any action assuming your views have their final frames before that method is called: for example, if you try to aView setFrame: in your viewDidLoad it will probably fail/have no effect as autolayout changes its frame during laying out phase. Therefore, if you really need to change its frame, you should call setFrame: in/after viewDidLayoutSubviews

In short, if your concern is about alpha value of an image or imageView, viewDidLayoutSubviews is probably not the correct place. viewDidAppear seems to be more appropriate for this. viewDidAppear is pretty straighforward: when the view appears on the screen, it is called.

Mert Buran
  • 2,989
  • 2
  • 22
  • 34
2

Have you tried to read the docs? viewDidLayoutSubviews, setNeedsLayout etc?

Button label change -> width change -> rearrange -> viewDidLayoutSubviews. You should not treat viewDidLayoutSubviews as a single call event. You should start an image transparency animation in viewDidAppear with UIView.animateWithDuration, it is a good place to start it, since everything is aligned properly. Let the image alpha be 0 in IB or init method and then just animate it.

Sega-Zero
  • 3,034
  • 2
  • 22
  • 46
  • I would like to invite you to answer this question http://stackoverflow.com/questions/32678975/need-assistance-regarding-viewdidlayoutsubviews – S.J Sep 20 '15 at 11:49
  • _"You should not treat viewDidLayoutSubviews as a single call"_ - This is critical. – bauerMusic Feb 23 '23 at 07:37