SwiftUI-ScrollView进化史

介绍

ScrollView 即滚动视图,在 iOS 开发中扮演着非常重要的角色。但在 SwiftUI 的发展史上,ScrollView 一直处于“残废”的状态,直到 SwiftUI 6.0 才逐渐补齐短板。下面详细讲解 SwiftUI 中 ScrollView 的进化史。

SwiftUI 1.0

可以垂直与水平滚动。

import SwiftUI

struct ContentView: View { 
    var body: some View {
        // 参数1:滚动方向,参数2:是否显示滚动条,参数3:滚动内容
        ScrollView(.vertical, showsIndicators: false) {
            Text("SwiftUI").padding(20)
            
            Divider()
            
            Rectangle()
                .foregroundColor(.orange)
                .frame(width: UIScreen.main.bounds.midX, height: 1500, alignment: .center)
            
            Divider()
            
            Text("Example")
        }
    }
}

SwiftUI 2.0

支持同时横向与纵向滚动。

import SwiftUI

struct ContentView: View {   
    var body: some View {
        ScrollView([.vertical, .horizontal], showsIndicators: false) {
            Text("SwiftUI").padding(20)
            
            Divider()
            
            Rectangle()
                .foregroundColor(.orange)
                .frame(width: 1500, height: 1500, alignment: .center)
            
            Divider()
            
            Text("Example")
        }
    }
}

SwiftUI 3.0

支持设置safeAreaInset

import SwiftUI

struct ContentView: View {
    var body: some View {
        ScrollView {
            Color
                .orange
                .frame(width: UIScreen.main.bounds.width, height: 1500)
        }
        .safeAreaInset(edge: .top) { // 顶部contentInset
            VStack {
                Text("顶部")

                Divider()
                    .frame(height: 5)
                    .background(.blue)
            }
            .background(.bar) // 选择bar
        }
        .safeAreaInset(edge: .bottom) { // 底部contentInset
            VStack {
                Divider()
                    .frame(height: 5)
                    .background(.blue)

                Text("底部")
            }
            .background(.green) // 选择颜色
        }
    }
}

SwiftUI 4.0

  • 可以控制是否可以滚动。
  • 可以控制滚动时键盘的隐藏方式。
  • 可以控制滚动条的显隐。
import SwiftUI

struct ContentView: View {
    @State private var name: String = "ZhangSan"

    var body: some View {
        ScrollView {
            TextField("请输入用户名", text: $name)
                .textFieldStyle(.roundedBorder)
                .padding()

            Color
                .orange
                .frame(height: 1500)
        }
        .scrollDisabled(false)
        .scrollDismissesKeyboard(.immediately)
        .scrollIndicators(.visible)
    }
}

SwiftUI 5.0

  • 新增scrollTargetBehavior修饰符,用于实现滚动时的行为,如对齐、分页。
  • 新增scrollTargetLayout修饰符,用于告知 ScrollView 偏移的参照者,常用于修饰 ScrollView 中的各种 Stack。
import SwiftUI

struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            LazyHStack {
                ForEach(0 ..< 10) { i in
                    RoundedRectangle(cornerRadius: 25)
                        .fill(Color(hue: Double(i) / 10, saturation: 1, brightness: 1).gradient)
                        .frame(width: 300, height: 300)
                }
            }
            .scrollTargetLayout()
        }
        .scrollTargetBehavior(.paging) // 分页
        .padding()
    }
}
  • 新增scrollPosition修饰符,用于设置内容的偏移与滚动后内容停留的位置。
import SwiftUI

struct ContentView: View {
    @State private var scrolledID: Int? = 0

    var body: some View {
        VStack {
            Button("Scroll") {
                withAnimation(.smooth) {
                    scrolledID = Int.random(in: 1 ..< 100)
                }
            }

            ScrollView {
                ForEach(1 ..< 100, id: \.self) { number in
                    Text(number.formatted())
                        .font(.title)
                        .foregroundColor(.white)
                        .frame(width: 300, height: 180)
                        .background(RoundedRectangle(cornerRadius: 8).fill(Color.purple))
                }
            }
            .scrollTargetLayout()
        }
        .scrollPosition(id: $scrolledID)
    }
}
  • 新增scrollTransition修饰符,用于设置滚动时的效果。
import SwiftUI

struct ContentView: View {
    var body: some View {
        ScrollView {
            ForEach(1 ..< 100, id: \.self) { number in
                Text(number.formatted())
                    .font(.title)
                    .foregroundColor(.white)
                    .frame(width: 300, height: 300)
                    .background(RoundedRectangle(cornerRadius: 8).fill(Color.purple))
                    .scrollTransition(topLeading: .animated, bottomTrailing: .interactive) { view, phase in
                        view
                          .scaleEffect(phase != .identity ? 0.6 : 1)
                          .opacity(phase != .identity ? 0.2 : 1)
                    }
            }
        }
    }
}
  • 新增scrollClipDisabled修饰符,防止超出范围的内容被裁切。
import SwiftUI

struct ContentView: View {
    let colors: [Color] = [.red, .orange, .yellow, .green, .teal, .blue, .purple]

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 20) {
                ForEach(colors, id: \.self) { color in
                    Rectangle()
                        .frame(width: 100, height: 100)
                        .foregroundStyle(color)
                        .shadow(color: .black.opacity(0.6), radius: 20)
                }
            }
        }
        .scrollClipDisabled(true)
        .padding()
    }
}
  • 新增scrollIndicatorsFlash修饰符,用于使滚动指示器闪现一下。
import SwiftUI

struct ContentView: View {
    @State private var showFlash = false

    var body: some View {
        HStack {
            Button("Flash") {
                withAnimation(.smooth) {
                    showFlash.toggle()
                }
            }

            ScrollView {
                ForEach(1 ..< 100, id: \.self) { number in
                    Text(number.formatted())
                        .font(.title)
                        .foregroundColor(.white)
                        .frame(width: 300, height: 180)
                        .background(RoundedRectangle(cornerRadius: 8).fill(Color.purple))
                }
            }
            .scrollIndicatorsFlash(trigger: showFlash)
        }
    }
}
  • 新增defaultScrollAnchor修饰符,用于设置内容的默认显示位置。
import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(spacing: 20) {
            // 默认从1开始显示
            ScrollView(.horizontal) {
                HStack {
                    ForEach(1 ..< 100, id: \.self) { number in
                        Text(number.formatted())
                            .font(.title)
                            .foregroundColor(.white)
                            .frame(width: 60, height: 60)
                            .background(RoundedRectangle(cornerRadius: 8).fill(Color.purple))
                    }
                }
            }

            // 默认从99开始显示
            ScrollView(.horizontal) {
                HStack {
                    ForEach(1 ..< 100, id: \.self) { number in
                        Text(number.formatted())
                            .font(.title)
                            .foregroundColor(.white)
                            .frame(width: 60, height: 60)
                            .background(RoundedRectangle(cornerRadius: 8).fill(Color.green))
                    }
                }
            }
            .defaultScrollAnchor(.trailing)
    }
}

SwiftUI 6.0

  • 新增 ScrollPosition 类型,配合scrollPosition修饰符,可以设置滚动后内容停留的位置。
import SwiftUI

struct ContentView: View {
    @State private var position: ScrollPosition = .init(idType: Int.self)

    var body: some View {
        VStack {
            HStack(spacing: 20) {
                Button("Scroll") {
                    withAnimation(.smooth) {
                        position.scrollTo(id: 66, anchor: .center) // 改变ScrollPosition即可滚动到指定的内容位置
                    }
                }

                Button("Scroll Offset") {
                    withAnimation(.smooth) {
                        position.scrollTo(point: CGPoint(x: 0, y: 1000)) // 跳转到某个位置点
                        position.scrollTo(x: 0) // 也可以单独指定x与y
                        position.scrollTo(y: 10000) // 也可以单独指定x与y
                    }
                }

                Button("Top") {
                    withAnimation(.smooth) {
                        position.scrollTo(edge: .top) // 回到顶部
                    }
                }

                Button("Bottom") {
                    withAnimation(.smooth) {
                        position.scrollTo(edge: .bottom) // 回到底部
                    }
                }
            }

            ScrollView {
                ForEach(1 ..< 100, id: \.self) { number in
                    Text(number.formatted())
                        .font(.title)
                        .foregroundColor(.white)
                        .frame(width: 300, height: 180)
                        .background(RoundedRectangle(cornerRadius: 8).fill(Color.purple))
                }
            }
            .scrollPosition($position) // 传入ScrollPosition类型
            .animation(.default, value: position)
        }
    }
}
  • 新增onScrollPhaseChange修饰符,用于监听 ScrollView 状态的改变。其中状态的类型为ScrollPhase,共有 5 种状态,分别为idletrackinginteractingdeceleratinganimating
import SwiftUI

struct ContentView: View {
    var body: some View {
        ScrollView {
            ForEach(1 ..< 100, id: \.self) { number in
                Text(number.formatted())
                    .font(.title)
                    .foregroundColor(.white)
                    .frame(width: 300, height: 180)
                    .background(RoundedRectangle(cornerRadius: 8).fill(Color.purple))
            }
        }
        .onScrollPhaseChange { oldPhase, newPhase, context in
            switch newPhase {
            case .idle:
                print("newPhase idle") // 未移动或者未交互
            case .tracking:
                print("newPhase tracking") // 滚动事件即将发生
            case .interacting:
                print("newPhase interacting") // 滚动但手指未离开
            case .decelerating:
                print("newPhase decelerating") // 加速松开手指,滚动减速
            case .animating:
                print("newPhase animating") // 向一个特定View移动
            }

            if newPhase.isScrolling {
                print("scrolling")
            }
        }
    }
}
  • 新增onScrollGeometryChange修饰符,用于监听 ScrollGeometry 的改变。通过 ScrollGeometry 可以获取 ScrollView 当前的boundscontainerSizecontentInsetscontentOffsetcontentSize以及visibleRect
import SwiftUI

struct ContentView: View {
    @State private var offset: CGFloat = 0

    var body: some View {
        ZStack(alignment: .top) {
            Rectangle()
                .fill(Color.red)
                .frame(height: 300 + max(0, -offset))
                .transformEffect(.init(translationX: 0, y: -max(0, offset)))

            ScrollView {
                Rectangle()
                    .fill(Color.clear)
                    .frame(height: 300)

                Text("\(offset)")
                
                

                ForEach(1 ..< 100, id: \.self) { number in
                    Text(number.formatted())
                        .font(.title)
                }
            }
            .onScrollGeometryChange(for: CGFloat.self, of: { geometry in
                geometry.contentOffset.y + geometry.contentInsets.top
            }, action: { _, newValue in
                offset = newValue
            })
        }
    }
}
  • 新增onScrollVisibilityChange修饰符,用于监听 ScrollView 可视内容的改变。
import SwiftUI

struct ContentView: View {
    var body: some View {
        ScrollView {
            ForEach(1 ..< 100, id: \.self) { number in
                Text(number.formatted())
                    .font(.title)
                    .foregroundColor(.white)
                    .frame(width: 300, height: 180)
                    .background(RoundedRectangle(cornerRadius: 8).fill(Color.purple))
                    .onScrollVisibilityChange(threshold: 0.5) { status in
                        if status {
                            print("\(number) is Visible")
                        }
                    }
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,063评论 6 510
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,805评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,403评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,110评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,130评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,877评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,533评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,429评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,947评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,078评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,204评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,894评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,546评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,086评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,195评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,519评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,198评论 2 357

推荐阅读更多精彩内容