# onScrollGeometryChange 讓拾音錄久了當掉

> 拾音的即時逐字稿用 SwiftUI 的 onScrollGeometryChange 判斷要不要跟著捲到最新，錄音約 20 分鐘時整個 app 當掉，AppKit 丟出 _postWindowNeedsUpdateConstraints。原因是捲動位置每變一點，動作就在排版途中觸發一次。改成只在「跟不跟」變了才觸發，動作從每秒 15 次降到只剩使用者捲動的那幾次。

- 網址：https://www.weibuilds.com/blog/swiftui-scroll-geometry-crash/
- 作者：weiwei
- 日期：2026-11-27
- 主題：前端介面
- 標籤：shiyin、swiftui、macos、appkit

11 月 25 日有人在 GitHub 回報：Mac 版拾音 5.1.1 錄音約 20 分鐘、主視窗在背景時，整個 app 當掉。AppKit 丟出的例外是 `-[NSWindow(NSDisplayCycle) _postWindowNeedsUpdateConstraints]`，意思是同一輪畫面更新裡，視窗要求重新計算排版的次數超過上限，AppKit 直接放棄。回報者附了主執行緒的呼叫堆疊，往上追是 SwiftUI 的 `ScrollActionDispatcher` 跑完動作之後要求立刻更新。這是 `onScrollGeometryChange` 的動作，拾音裡只有即時逐字稿用到它。

## 跟著最新的寫法

即時逐字稿會一直長，使用者停在底部時要跟著捲到最新；往上捲回去看，就不要把他拉回來。原本的寫法是讓轉換回傳三個數字：捲了多少、內容多高、看得到的底部在哪，動作裡再判斷：

```swift
.onScrollGeometryChange(for: LivePosition.self) { geometry in
    LivePosition(offset: geometry.contentOffset.y, content: geometry.contentSize.height,
                 bottom: geometry.visibleRect.maxY)
} action: { old, new in
    if new.bottom >= new.content - 40 {
        if !followLatest { followLatest = true }
    } else if new.offset < old.offset - 1 && new.content >= old.content {
        if followLatest { followLatest = false }
    }
}
```

規則本身沒有錯：離底部 40 點內就跟，往上捲而且內容沒有變短就不跟。`followLatest` 變成 false 時，畫面右下角會出現「回到最新」的按鈕。

## 排版一直收斂不了

<figure>
<svg class="diagram" viewBox="0 0 760 300" role="img" aria-label="改之前的循環。即時逐字稿用 LazyVStack，列高先估、捲到看得見才量。量完內容高度變了，捲動位置跟著調整。轉換回傳的三個小數因此變了，動作在排版途中觸發，要求立刻再更新一次，動作裡還可能改 followLatest，讓「回到最新」按鈕出現或消失，又改變排版。這個循環在同一輪畫面更新裡一直跑，次數超過上限，AppKit 丟出例外，app 結束。" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <marker id="sg-ar" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0L10 5L0 10z" fill="var(--ink-2)"/></marker>
  </defs>
  <g font-size="13" font-family="inherit" fill="var(--ink)">
    <text x="20" y="22" font-size="12" fill="var(--ink-2)">同一輪畫面更新裡</text>
    <rect x="20" y="36" width="230" height="56" rx="6" fill="var(--paper-2)" stroke="var(--rule)"/>
    <text x="135" y="59" text-anchor="middle" font-weight="600">LazyVStack 量到新的列</text>
    <text x="135" y="79" text-anchor="middle" font-size="12" fill="var(--ink-2)">列高先估，看得見才量</text>
    <line x1="250" y1="64" x2="298" y2="64" stroke="var(--ink-2)" stroke-width="1.6" marker-end="url(#sg-ar)"/>
    <rect x="300" y="36" width="200" height="56" rx="6" fill="var(--paper-2)" stroke="var(--rule)"/>
    <text x="400" y="59" text-anchor="middle" font-weight="600">內容高度變了</text>
    <text x="400" y="79" text-anchor="middle" font-size="12" fill="var(--ink-2)">捲動位置跟著調</text>
    <line x1="500" y1="64" x2="548" y2="64" stroke="var(--ink-2)" stroke-width="1.6" marker-end="url(#sg-ar)"/>
    <rect x="550" y="36" width="190" height="56" rx="6" fill="var(--paper-2)" stroke="var(--rule)"/>
    <text x="645" y="59" text-anchor="middle" font-weight="600">轉換回傳的小數變了</text>
    <text x="645" y="79" text-anchor="middle" font-size="12" fill="var(--ink-2)">offset、content、bottom</text>
    <line x1="645" y1="92" x2="645" y2="140" stroke="var(--ink-2)" stroke-width="1.6" marker-end="url(#sg-ar)"/>
    <rect x="460" y="142" width="280" height="56" rx="6" fill="var(--paper-2)" stroke="var(--accent)"/>
    <text x="600" y="165" text-anchor="middle" font-weight="600">動作在排版途中觸發</text>
    <text x="600" y="185" text-anchor="middle" font-size="12" fill="var(--ink-2)">要求立刻再更新一次</text>
    <line x1="460" y1="170" x2="402" y2="170" stroke="var(--ink-2)" stroke-width="1.6" marker-end="url(#sg-ar)"/>
    <rect x="130" y="142" width="270" height="56" rx="6" fill="var(--paper-2)" stroke="var(--accent)"/>
    <text x="265" y="165" text-anchor="middle" font-weight="600">當下改 followLatest</text>
    <text x="265" y="185" text-anchor="middle" font-size="12" fill="var(--ink-2)">「回到最新」按鈕出現或消失</text>
    <path d="M130 170 H80 V100" fill="none" stroke="var(--ink-2)" stroke-width="1.6" marker-end="url(#sg-ar)"/>
    <text x="72" y="140" text-anchor="end" font-size="12" fill="var(--ink-2)">再排</text>
    <rect x="130" y="232" width="610" height="50" rx="6" fill="none" stroke="var(--accent)"/>
    <text x="435" y="262" text-anchor="middle">次數超過上限 → _postWindowNeedsUpdateConstraints → app 結束</text>
    <line x1="600" y1="198" x2="600" y2="230" stroke="var(--accent)" stroke-width="1.6" stroke-dasharray="4 3"/>
  </g>
</svg>
<figcaption>觸發動作和改狀態都發生在排版途中，後來改掉的就是這兩步。</figcaption>
</figure>

問題在那三個數字是小數。即時逐字稿用 `LazyVStack`，每一列的高度先用估的，捲到看得見才真的量。量完內容高度變了，捲動位置跟著調整，轉換回傳的值就不一樣，動作又觸發一次，而且是在排版途中。動作裡改 `followLatest` 會讓「回到最新」出現或消失，排版又要重來。大多數時候轉幾圈就停了，只要有一次停不下來，AppKit 就放棄。

我寫了一個壓力測試，每秒塞 6 行長短不一的假文字、未定稿的字每秒變 20 次，跑了 18 分鐘也沒當掉，跟回報者一樣重現不出來。改用次數驗：同樣跑 120 秒，捲動位置變了 1827 次，動作跑了 1772 次，等於每秒約 15 次在排版途中要求更新。正常的跟捲根本不需要這麼多次。

## 只在「跟不跟」變了才觸發

<figure>
<svg class="diagram" viewBox="0 0 760 230" role="img" aria-label="改之後的流程。捲動位置一變，轉換就把位置交給 LiveFollow，LiveFollow 是放在 State 裡的一般 class，不是 Observable，改它不會讓畫面重算。它記著上一次的位置，照同樣的規則算出跟或不跟，轉換只回傳這個布林值。布林值沒變就不觸發動作；變了才觸發，動作用 DispatchQueue.main.async 等這一輪排版結束再改 followLatest。120 秒的壓力測試裡，位置變了 1687 次，動作只跑了 36 次，就是往上捲和捲回底部的次數。" xmlns="http://www.w3.org/2000/svg">
  <defs>
    <marker id="sf-ar" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0L10 5L0 10z" fill="var(--ink-2)"/></marker>
  </defs>
  <g font-size="13" font-family="inherit" fill="var(--ink)">
    <rect x="20" y="20" width="170" height="56" rx="6" fill="var(--paper-2)" stroke="var(--rule)"/>
    <text x="105" y="43" text-anchor="middle" font-weight="600">捲動位置變了</text>
    <text x="105" y="63" text-anchor="middle" font-size="12" fill="var(--ink-2)">120 秒裡 1687 次</text>
    <line x1="190" y1="48" x2="238" y2="48" stroke="var(--ink-2)" stroke-width="1.6" marker-end="url(#sf-ar)"/>
    <rect x="240" y="20" width="260" height="56" rx="6" fill="var(--topic-frontend)"/>
    <text x="370" y="43" text-anchor="middle" font-weight="600" fill="var(--paper)">轉換裡的 LiveFollow</text>
    <text x="370" y="63" text-anchor="middle" font-size="12" fill="var(--paper)">記著上一次的位置，只回傳跟不跟</text>
    <line x1="500" y1="48" x2="548" y2="48" stroke="var(--ink-2)" stroke-width="1.6" marker-end="url(#sf-ar)"/>
    <rect x="550" y="20" width="190" height="56" rx="6" fill="var(--paper-2)" stroke="var(--rule)"/>
    <text x="645" y="43" text-anchor="middle" font-weight="600">布林值變了嗎</text>
    <text x="645" y="63" text-anchor="middle" font-size="12" fill="var(--ink-2)">沒變就不觸發動作</text>
    <line x1="645" y1="76" x2="645" y2="124" stroke="var(--ink-2)" stroke-width="1.6" marker-end="url(#sf-ar)"/>
    <text x="657" y="104" font-size="12" fill="var(--ink-2)">變了（36 次）</text>
    <rect x="370" y="126" width="370" height="56" rx="6" fill="var(--paper-2)" stroke="var(--rule)"/>
    <text x="555" y="149" text-anchor="middle" font-weight="600">動作：DispatchQueue.main.async</text>
    <text x="555" y="169" text-anchor="middle" font-size="12" fill="var(--ink-2)">等這一輪排版結束，再改 followLatest</text>
    <rect x="20" y="126" width="310" height="86" rx="6" fill="none" stroke="var(--rule)" stroke-dasharray="5 4"/>
    <text x="36" y="150" font-size="12" fill="var(--ink-2)">LiveFollow 放在 @State，是一般的 class</text>
    <text x="36" y="172" font-size="12" fill="var(--ink-2)">不是 @Observable，改它不會讓畫面重算</text>
    <text x="36" y="194" font-size="12" fill="var(--ink-2)">「回到最新」按下去時也把它設成跟</text>
  </g>
</svg>
<figcaption>規則跟原本一樣，只是從動作搬進轉換。</figcaption>
</figure>

改法是把判斷搬進轉換，轉換只回傳「跟不跟」這個布林值。判斷需要上一次的位置，我放在一個一般的 class 裡，存在 `@State`：

```swift
.onScrollGeometryChange(for: Bool.self) { geometry in
    liveFollow.update(offset: geometry.contentOffset.y, content: geometry.contentSize.height,
                      bottom: geometry.visibleRect.maxY)
} action: { _, follow in
    DispatchQueue.main.async { if followLatest != follow { followLatest = follow } }
}

final class LiveFollow {
    var following = true
    private var last: (offset: CGFloat, content: CGFloat)?

    func update(offset: CGFloat, content: CGFloat, bottom: CGFloat) -> Bool {
        defer { last = (offset, content) }
        if bottom >= content - 40 {
            following = true
        } else if let last, offset < last.offset - 1, content >= last.content {
            following = false
        }
        return following
    }
}
```

它刻意不是 `@Observable`。轉換在排版途中執行，在這裡改一個會被觀察的值，等於又叫 SwiftUI 重算一次畫面。動作裡也不當下改狀態，丟到下一輪主執行緒再改。按「回到最新」時要同時把 `liveFollow.following` 設成 true，不然捲動沒剛好停在底部 40 點內時，兩邊會不一致，之後往上捲也觸發不了動作。

我也考慮過 `onScrollPhaseChange`，使用者一開始捲就停止跟。可是一般滑鼠的滾輪沒有觸控板那種捲動階段，算不算「捲動中」我不確定，判斷不了是不是往上捲，就沒用。

同樣的壓力測試再跑 120 秒，位置變了 1687 次，動作只跑了 36 次，剛好是測試裡往上捲、捲回底部的次數。接真的語音辨識跑 60 秒，未定稿的字每秒變約 2.5 次，動作只觸發 1 次，畫面一直停在底部跟著最新。修正在隔天跟著 5.2.2 發布，回報和完整的呼叫堆疊在 [GitHub #23](https://github.com/juinwei7/Shiyin/issues/23)。
