You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中水平ScrollView如何在内部Text更新时自动滚动到末尾

实现方案

核心逻辑是通过onChange修饰符监听模型中combinedString的变化,一旦值更新就自动执行滚动逻辑,不需要手动点击按钮,实现代码如下:

struct ContentView: View {
    @ObservedObject var model: Model
    
    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            TextField("First string: ", text: $model.firstString)
            TextField("Second string: ", text: $model.secondString)
            Spacer().frame(height: 20)
            Text("Combined string:")
            ScrollViewReader { scrollView in
                ScrollView(.horizontal) {
                    Text(model.combinedString)
                        .id("combinedText")
                }
                // 监听组合文本的变化,自动触发滚动到末尾
                .onChange(of: model.combinedString) { _ in
                    withAnimation {
                        scrollView.scrollTo("combinedText", anchor: .trailing)
                    }
                }
            }
        }
    }
}

如果需要兼容iOS 14以下版本,可以将onChange替换为onReceive实现同样效果:

// iOS 14以下兼容写法
.onReceive(model.$combinedString) { _ in
    withAnimation {
        scrollView.scrollTo("combinedText", anchor: .trailing)
    }
}

内容的提问来源于stack exchange,提问作者Khawer K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:54:08