-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathViewHighlighter_ScrollViewExample_Dynamic.swift
74 lines (59 loc) · 2.29 KB
/
ViewHighlighter_ScrollViewExample_Dynamic.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
// SwiftUIView.swift
//
//
// Created by msz on 2023/01/24.
//
import SwiftUI
@available(iOS 15.0, *)
struct ViewHighlighter_ScrollViewExample_Dynamic: View {
var catImageURLs: [String] = [
"https://placekitten.com/1200/1200",
"https://placekitten.com/1100/1100",
"https://placekitten.com/1000/1000",
"https://placekitten.com/1500/1500",
"https://placekitten.com/800/800"
]
@State var currentSpot: Int? = 0
var body: some View {
ScrollViewReader { proxy in
ScrollView {
ForEach(catImageURLs, id: \.self) { imageURL in
AsyncImage(url: URL(string: imageURL)) { loadedImage in
loadedImage
.resizable()
.scaledToFit()
.cornerRadius(20)
.frame(width: 300, height: 300)
} placeholder: {
ProgressView()
}
.id(imageURL)
.addSpotlight(catImageURLs.firstIndex(of: imageURL) ?? -1, text: "This is the cat image with URL \(imageURL)")
}
}
.applySpotlightOverlay(currentSpot: $currentSpot)
.onChange(of: currentSpot) { newValue in
guard let newValue else { return }
withAnimation {
// scroll to make sure the current spotlight is visible
if newValue < catImageURLs.count {
proxy.scrollTo(catImageURLs[newValue], anchor: .bottom)
}
// at the last spotlight (index + 1), scroll to the very top
if newValue == catImageURLs.count,
let firstCatImageID = catImageURLs.first
{
proxy.scrollTo(firstCatImageID, anchor: .top)
}
}
}
}
}
}
@available(iOS 15.0, *)
struct ViewHighlighter_ScrollViewExample_Dynamic_Previews: PreviewProvider {
static var previews: some View {
ViewHighlighter_ScrollViewExample_Dynamic()
}
}