2

I'm creating a UIView in one of my methods and going through all the steps of adding it to the view:

background1 = UIView(frame: CGRectInset(other.frame, -thickness, -thickness))
background1!.backgroundColor = aColor   
background1!.hidden = false
container.addSubview(background1!)

This is included in a method I call in viewDidAppear(). In general, everything works perfectly. This view, however, appears noticeably later when opening the app the first time.

I can tell, from setting breakpoints before and after the above code, that background1 does not appear on the screen immediately after the code is executed, nor even in any place I've been able to set breakpoints.

I'm not doing anything else with the view—for some reason it takes surprisingly annoyingly long to load.

I have a very complicated (as shown by the >114 comments here) layout setup that's part AutoLayout and part programmatic and thus would like to just resolve this issue alone, if possible, without ripping up everything else.

I know that viewDidAppear() is, of course, called after the view appears, meaning the code executed should take effect then, but from what I can tell, background1 isn't even appearing at that point.

Additionally, as you can see in the first line of the code I posted, background1's frame relies upon that that of other, another subview. This view has its frame determined by AutoLayout. From what I understand, it's only guaranteed that the correct frame will be reported after viewDidLayoutSubviews()is called. (Incidentally, this is even called after viewDidLoad().)

I know I've already made a mistake by mixing AutoLayout and programmatic layout, but I'm hoping there's a way to salvage this. I do, in fact, remember, a time in a previous version when nearly the exact same setup was working perfectly. (Looking back through commits, though, I couldn't find it.)

To be clear, I guess I'm asking if there's a way to force the UIView to appear when the code is executed. I've tried calling the parent's layoutSubviews(), but that doesn't seem to work.

Thank you.

Community
  • 1
  • 1
Randoms
  • 2,110
  • 2
  • 20
  • 31
  • Can you add the view in `viewWillAppear` rather than `viewDidAppear`? – Paulw11 Jan 03 '16 at 06:18
  • @Paulw11 My thinking exactly. The issue with that, though, is that the frame of other view which this view's frame depends on hasn't been set by AutoLayout at that time. – Randoms Jan 03 '16 at 06:26
  • Then you should use autolayout for this view too so that the layout can all be resolved at the same time. – Paulw11 Jan 03 '16 at 06:30
  • You should create and add this view in viewWillAppear (or in viewDidLoad, it would be much elegant), and if you don't want to layout it, then set its frame in viewDidLayoutSubviews method. – Péter Kovács Jan 03 '16 at 10:20
  • What happens if you add it as a subview of `other` instead of `container` and use `other.bounds` for the calcualation? – chedabob Jan 03 '16 at 11:22

0 Answers0