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
相关产品推荐
相关产品推荐

