In SwiftUI, a text field empties whenever its parent toggles a highlight using if/else around the same child view; why, and how do you fix it?
answer
- two branches, two views
- conditional content from the view builder
- put the condition in the argument
- or hoist the text into the parent
basics
~20 sEach if/else branch is a separate structural identity, so flipping the condition replaces the child with a new one whose @State starts empty. Keep one view and put the condition inside the modifier's argument, or hoist the text into the parent.
solid answer
~50 sCode like `if isFlagged { DraftField().border(.red) } else { DraftField() }` looks like one field with an optional border, but SwiftUI's view builder turns `if`/`else` into conditional content with two slots, and each slot has its own structural identity. When `isFlagged` flips, SwiftUI removes the view in one branch and inserts the one in the other, so the `@State` text inside `DraftField` starts from `""`, focus is lost and `onAppear` runs again. The fix is to keep one view and move the condition into a value: `DraftField().border(isFlagged ? Color.red : Color.clear)`. Changing a modifier's argument keeps the identity, so the text survives and the change can animate. If the field must survive genuinely different layouts, hoist the text into the parent's `@State` and pass a binding. Keep `if` for branches that really are different views.
code
swift · 26 linesstruct DraftField: View {
@State private var text = ""
var body: some View {
TextField("Reply", text: $text)
.textFieldStyle(.roundedBorder)
.onAppear { print("DraftField appeared") }
}
}
struct ReplyBar: View {
@State private var isFlagged = false
var body: some View {
VStack {
Toggle("Flag reply", isOn: $isFlagged)
// Broken: two branches, two identities; each flip empties the text.
// if isFlagged { DraftField().border(.red) } else { DraftField() }
// Fixed: one view; only the modifier's argument changes.
DraftField()
.border(isFlagged ? Color.red : Color.clear, width: 2)
}
}
}go deeper
Recall that the two branches of an if/else are two different views, so state inside them does not carry across a flip.
Explain conditional content: the builder makes two slots, each with its own identity, while a ternary in a modifier argument keeps one view and only changes an input.
Diagnose the reset from symptoms such as onAppear firing on each toggle or lost focus, and choose between a neutral modifier value, hoisting state, and keeping the container type fixed.
Weigh where shared helpers hide identity changes: a convenience that branches internally spreads resets to every screen, so review such helpers and prefer value-driven modifiers.
## The symptom A reply bar has a text field and a "Flag reply" toggle. When the reply is flagged, the field gets a red border. The code reads naturally: ```swift if isFlagged { DraftField().border(.red) } else { DraftField() } ``` A user types half a reply, flips the toggle, and the text is gone. Focus is gone too, and if `DraftField` logs in `onAppear`, the log fires on every flip. Nothing in the code clears the text. ## Why the text disappears `body` is built by SwiftUI's view builder. An `if`/`else` inside it produces **conditional content** with two slots: the builder's `buildEither(first:)` and `buildEither(second:)` return a `_ConditionalContent` value that holds whichever branch is active. Each slot is a different position in the hierarchy, so each has its own **structural identity**, even though both branches create a `DraftField`. When `isFlagged` flips, SwiftUI is not updating one field; it removes the view in one branch and inserts the view in the other. Apple's documentation on transitions names `.id`, `if` and `switch` as identity-affecting changes that reset the state of the view they are applied to. For the field that means: - its `@State` text starts again from `""`; - any `@FocusState` it holds resets, so the keyboard focus is lost; - `onDisappear` runs for the old field and `onAppear` for the new one; - an unfinished `task` in the field is cancelled; - the border does not animate in; the change shows as a removal and insertion. ## The fix: one view, conditional values Keep one `DraftField` and move the condition into the modifier's argument: ```swift DraftField() .border(isFlagged ? Color.red : Color.clear, width: 2) ``` The same rule covers other modifiers: `opacity(isHidden ? 0 : 1)` instead of an `if` that removes the view keeps its state while hiding it (a view at zero opacity still takes part in layout), and `disabled(isLocked)` replaces two branches where one is disabled. Now the code always produces the same type at the same position. Only an input changes, and changing an input updates the view in place, so the text, the focus and any running work survive, and the change can animate. | Approach | Identities | Child's `@State` | Animation | |---|---|---|---| | `if`/`else` around the same child | Two | Reset on each flip | Removal and insertion | | Ternary inside the modifier's argument | One | Kept | In place | | Text hoisted to the parent, binding passed down | Whatever the child's structure gives | Child may reset; the text survives in the parent | Depends on the child's structure | | Hand-written helper that applies a modifier only when true | Two (it hides an `if`/`else`) | Reset on each flip | Removal and insertion | ## When the modifier has no neutral value Most modifiers have an "off" value: `Color.clear`, an opacity of `1`, a padding of `0`, `disabled(false)`, `lineLimit(nil)`. When one does not, choose deliberately: 1. **Hoist the state.** Store the draft in the parent's `@State` and pass a `Binding`. The child can then be replaced without losing the text. 2. **Keep the container, vary its contents.** Switching between `HStack` and `VStack` with `if`/`else` has the same problem; the lesson on custom layouts covers `AnyLayout`, which changes the layout type without destroying the subviews' state. 3. **Accept the reset.** If the two branches really are different screens, starting fresh may be the correct behaviour. ## When `if`/`else` is the right tool Branches are correct when the content is genuinely different: a sign-in form versus the signed-in home, an empty state versus a list. There, a fresh identity is what you want, and the lesson on insertion transitions covers how to animate the swap. The defect is only the case where both branches mean "the same thing, styled differently". ## Diagnosing it in a real app 1. Add `onAppear` and `onDisappear` logging to the child. An in-place update logs nothing; a replacement logs a disappearance and an appearance on every flip. 2. Look for the same view type in both branches of an `if`, `switch` or ternary between two `AnyView` values; `AnyView`'s documentation says a change of the wrapped type destroys the old hierarchy and creates a new one. 3. Check team helpers that "apply a modifier conditionally": if they contain an `if`/`else`, every caller inherits the reset.
- Does a switch in body cause the same reset as if/else?Yes. Each case is its own slot of conditional content, so moving from one case to another replaces the view and resets its state, exactly like an `if`/`else`. Apple's documentation on transitions lists `.id`, `if` and `switch` together as identity-affecting changes that reset a view's state.
- Why is a team helper that applies a modifier only when a condition is true a trap?Inside, such a helper is an `if`/`else` that returns either the modified or the plain content, which are two branches with different identities. Every call site whose condition changes at runtime therefore resets the wrapped view's state and swaps it instead of animating. A modifier that takes the condition as an argument and uses a neutral value avoids this.
- An if/else around the same view type keeps one identity
- The field empties because the parent's body ran again
- Wrapping both branches in AnyView keeps the child's state
- A ternary inside a modifier's argument also creates two views
- Making the child's @State private stops it resetting on a branch flip