A UIKit call screen adds participant tiles in viewDidLayoutSubviews() and starts a repeating hide-controls timer in viewWillAppear(_:); why do tiles duplicate and controls hide erratically?
answer
- count how often each callback runs
- layout passes are not one per appearance
- the run loop keeps a scheduled timer
- invalidate before you schedule again
- build once, pair start with stop
basics
~20 sviewDidLayoutSubviews() runs on every layout pass, not once, so tiles are added again on each rotation or inset change. viewWillAppear(_:) runs on every appearance, so each return schedules another timer while the old ones keep firing.
solid answer
~40 sBoth bugs are setup placed in callbacks that repeat. `viewDidLayoutSubviews()` follows every `layoutSubviews()` of the view: during a transition, on rotation or window resize, when safe area insets change, and whenever something calls `setNeedsLayout()`. Adding tiles there adds a full new set each pass. `viewWillAppear(_:)` runs each time the screen reappears, for instance after a pushed screen is popped; a repeating `Timer` scheduled there is kept by the run loop until invalidated, so each appearance adds one more and they all fire. The fix: build tiles once in `viewDidLoad()`, keep layout callbacks to geometry, and pair the timer with its stop, starting in `viewDidAppear(_:)` and invalidating in `viewWillDisappear(_:)`, invalidating any old timer first.
code
swift · 22 linesimport UIKit
final class BrokenCallControlsViewController: UIViewController {
private var hideTimer: Timer?
var participantNames: [String] = []
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
for name in participantNames { // runs on every layout pass
let label = UILabel()
label.text = name
view.addSubview(label)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
hideTimer = Timer.scheduledTimer(withTimeInterval: 4, repeats: true) { _ in
print("hide controls") // the previous timer is never invalidated
}
}
}go deeper
Recall which callbacks run once and which run often, and keep view creation in viewDidLoad() rather than in layout callbacks.
Explain what triggers a layout pass and why a scheduled Timer survives losing your reference until it is invalidated.
Diagnose duplicate subviews and stacked timers from symptoms with hit-count breakpoints, and refactor setup into idempotent layout and balanced appear and disappear pairs.
Make callback placement a review checklist item, so repeated setup in layout or appearance callbacks is caught before it reaches users.
## The rule being broken The leaf's summary says it plainly: setup in the wrong callback causes repeated work or leaks. A UIKit view controller has callbacks with very different frequencies, and the bugs in this question come from treating two frequent ones as if they ran once. | Callback | How often it runs | Fit for | |---|---|---| | `viewDidLoad()` | once, when the view loads | building subviews, constraints, data sources | | `viewWillAppear(_:)`, `viewIsAppearing(_:)`, `viewDidAppear(_:)` | every appearance | starting per-appearance work | | `viewWillDisappear(_:)`, `viewDidDisappear(_:)` | every disappearance | stopping that work | | `viewWillLayoutSubviews()`, `viewDidLayoutSubviews()` | every layout pass, any number of times | adjusting geometry from the current bounds | ## Why the tiles duplicate `viewDidLayoutSubviews()` is called just after the view controller's view runs `layoutSubviews()`. Apple's documentation says layout can happen **multiple times during a transition, or at any time while the view is visible**. On a call screen, passes come from: - the initial presentation, which can run more than one pass; - rotation and iPad window resizing; - safe area changes, such as a bar being shown or hidden; - any code that calls `setNeedsLayout()` or `layoutIfNeeded()`, including a tile updating its own constraints. Each pass runs the loop that creates a tile per participant and adds it, so the view collects duplicate tiles stacked over each other. Adding subviews can itself schedule another layout pass, so the loop can feed itself. The cost is not only visual: every duplicate tile has its own renderer and memory. ## Why the controls hide erratically `viewWillAppear(_:)` runs on every appearance, including each time the user returns from a pushed participant-details screen. `Timer.scheduledTimer(withTimeInterval:repeats:block:)` adds the timer to the current run loop, which holds a strong reference to it; a repeating timer keeps firing until `invalidate()` is called. Assigning a new timer to `hideTimer` does not stop the old one, it only drops the property's reference, so after three appearances three repeating timers are live, each hiding the controls on its own schedule. If the timer's block captured the view controller strongly, the timers would also keep it alive after the screen closes; capturing `self` weakly avoids that, and the lesson on Swift reference cycles covers why. ## The fix 1. **Build once.** Create and add the tiles in `viewDidLoad()`. If tiles must change when participants join or leave, update them from the model change, not from a layout callback. 2. **Layout callbacks do geometry only.** In `viewDidLayoutSubviews()`, set frames or adjust values that depend on the current `view.bounds` and `view.safeAreaInsets`. Running that code ten times is harmless because it is idempotent. 3. **Pair start and stop.** Start the hide-controls timer in `viewDidAppear(_:)` and invalidate it in `viewWillDisappear(_:)`, or use `viewWillAppear(_:)` with `viewDidDisappear(_:)`; either pair is balanced. Invalidate any existing timer before scheduling a new one so a missed stop cannot stack timers. 4. **Guard what must not repeat.** When a one-off action truly needs final geometry, such as scrolling to the active speaker, put it in `viewIsAppearing(_:)`, which runs once per appearance, rather than in a layout callback with a flag. ## Related callbacks that also repeat Two more view controller callbacks, both available since iOS 11, behave like the layout ones and belong to the same rule: - `viewSafeAreaInsetsDidChange()` runs whenever the safe area insets change, such as when a bar appears or the window resizes. - `viewLayoutMarginsDidChange()` runs whenever the layout margins change. Both are declared as requiring a call to `super`, and both suit only geometry adjustments, never creating views or starting work. The same goes for a trait-change handler registered with `registerForTraitChanges(_:handler:)`, which can run several times in a session. ## How to find it - Log or set a breakpoint with a hit count in each callback; seeing `viewDidLayoutSubviews()` fire five times during one presentation is the usual surprise. - Check `tileStack.arrangedSubviews.count` or `view.subviews.count` after a rotation. - Log the timer's creation and each firing; several firings per interval mean stacked timers. The pattern to remember: build in `viewDidLoad()`, lay out in layout callbacks, and give every start on the appear side a matching stop on the disappear side.
- In UIKit, is it ever right to do work in viewDidLayoutSubviews() that depends on the view's size?Yes, as long as it is idempotent geometry: setting frames, corner radii or a collection view layout's item size from the current `view.bounds`. Running it on every pass then just recomputes the same values. Creating views, starting work or scrolling to a position is what must not live there, because each extra pass repeats it.
- In UIKit, why does assigning a new Timer to the same property not stop the previous timer?A scheduled `Timer` is retained by the run loop it was added to, not only by your property. Replacing the property's value drops your reference, but the run loop keeps the old timer and keeps firing it until `invalidate()` is called. Invalidating the old timer before scheduling the new one is the fix.
- viewDidLayoutSubviews() runs once, right after viewDidLoad()
- Layout callbacks only run when the device rotates
- Replacing a Timer property invalidates the previous timer
- UIKit stops a screen's timers when its view disappears
- Starting work in viewDidLoad() and stopping it in viewDidDisappear(_:) is balanced