I have tried different iterations of examples posted on this site but nothing is going right.
I have also tried following the examples listed here:
Navigation to new navigation types:
I am getting the warning in this posts' title for deprecation of NavigationLink(destination:isActive)
struct PhoneLogin: View {
#StateObject var phoneLoginData = PhoneLoginViewModel()
#State var isSmall = UIScreen.main.bounds.height < 750
var body: some View {
VStack {
VStack {
Text("Continue With Phone")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.black)
.padding()
Image("phone_logo")
.resizable()
.aspectRatio(contentMode: .fit)
.padding()
Text("You'll receive a 4-digit code \n to verify next")
.font(isSmall ? .none : .title2)
.foregroundColor(.gray)
.multilineTextAlignment(.center)
.padding()
// Mobile Number Field . . . . .
HStack {
VStack(alignment: .leading, spacing: 6) {
Text("Enter Your Number")
.font(.caption)
.foregroundColor(.gray)
Text("+ \(phoneLoginData.getCountryCode()) \(phoneLoginData.phNo)")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(.black)
}
Spacer(minLength: 0)
NavigationLink(
destination: Verification(phoneLoginData: phoneLoginData), isActive: $phoneLoginData.goToVerify) {
Text("")
.hidden()
}
Button(action: phoneLoginData.sendCode, label: {
Text("Continue")
.foregroundColor(.black)
.padding(.vertical, 18)
.padding(.horizontal, 38)
.background(Color.yellow)
.cornerRadius(15)
})
.disabled(phoneLoginData.phNo == "" ? true : false)
}
.padding()
.background(Color.white)
.cornerRadius(20)
.shadow(color: Color.black.opacity(0.1), radius: 5, x: 0, y: -5)
}
.frame(height: UIScreen.main.bounds.height / 1.8)
.background(Color.white)
.cornerRadius(20)
// Custom Number Pad
CustomNumberPad(value: $phoneLoginData.phNo, isVerify: false)
}
.background(Color("bg").ignoresSafeArea(.all, edges: .bottom))
}
}
I finally figured it out:
REPLACED:
NavigationLink(
destination: Verification(phoneLoginData: phoneLoginData),
isActive: $phoneLoginData.goToVerify) {
Text("")
.hidden()
}
WITH:
Making sure the below code is placed anywhere inside a NavigationStack (ios 16):
.navigationDestination(
isPresented: $phoneLoginData.goToVerify) {
Verification(phoneLoginData: phoneLoginData)
Text("")
.hidden()
}
I am trying to put grid(developed with scrollview) inside scrollview but I can't set grid height with content height. I can't handle this problem with .fixedsize()
GeometryReader{ reader in
ScrollView{
Text(reader.size.height.description)
Text(reader.size.height.description)
FlowStack(columns: 3, numItems: 27, alignment: .leading) { index, colWidth in
if index == 0{
Text(" \(index) ").frame(width: colWidth).border(Color.gray)
.background(Color.red)
}
else if index == 1{
Text(" \(index) ").frame(width: colWidth).border(Color.gray)
}
else if index == 2{
Text(" \(index) ").frame(width: colWidth).border(Color.gray)
}
else{
Text(" \(index) ").frame(width: colWidth).border(Color.gray)
}
}
.background(Color.red)
Text(reader.size.height.description)
Text(reader.size.height.description)
}.fixedSize(horizontal: false, vertical: false)
}
Result
What I want
I don't know what did you wrote in FlowStack struct, that's why it's really hard to give right answer. There is how I solve this grid:
struct GridScrollView: View {
var body: some View {
GeometryReader{ geometry in
VStack {
Text("height: \(geometry.size.height.description)")
Text("width: \(geometry.size.width.description)")
ScrollView{
FlowStack(columns: 3, numItems: 60, width: geometry.size.width, height: geometry.size.height)
}
}
}
}
}
my FlowStack code:
struct FlowStack: View {
var columns: Int
var numItems: Int
var width: CGFloat
var height: CGFloat
private var numberOfRows: Int {
get {
numItems / columns
}
}
private var cellWidth: CGFloat {
get {
width / CGFloat(columns) - 4 // with padding
}
}
private var cellHeight: CGFloat {
get {
height / CGFloat(numberOfRows) - 4 // with padding
}
}
var body: some View {
ForEach(0..<self.numberOfRows, id: \.self) { row in
HStack {
ForEach(1...self.columns, id: \.self) { col in
Text("\(row * self.columns + col)")
.frame(width: self.cellWidth, height: self.cellHeight, alignment: .center)
.background(Color.red)
.border(Color.gray)
.padding(2)
}
}
}
}
}
and the result is:
P.S. that's my quick solution. I think you can also use this grid from github, it's quite massive, but flexible in my opinion
I am trying out SwiftUI and I am building a holiday app in which you can see where have you been what was the weather like there and how long did you stay there.
The problem is that when I put my HolidayCard in NavigationLink all images disappear.
This is the code and the preview with navigation link
struct ContentView: View {
var body: some View {
NavigationView {
ScrollView {
ForEach(holidayData, id: \.id) { holiday in
NavigationLink(destination: HolidayDetails(holiday: holiday)) {
HolidayCard(holiday: holiday)
}
}
}
.navigationBarTitle(Text("My holidays"), displayMode: .large)
}
}
}
This is my HolidayCard and how should it look like
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 12) {
Spacer()
holiday.weatherImage
.resizable()
.frame(width: 48, height: 48)
VStack(alignment: .leading, spacing: 0) {
Text("\(holiday.city),")
.font(.headline)
.fontWeight(.bold)
Text(holiday.country)
.font(.subheadline)
}
Text("\(holiday.season.rawValue) · \(holiday.duration) days")
.font(.headline)
.fontWeight(.light)
}
.foregroundColor(Color.white)
.padding()
.background(Color.black.opacity(0.5))
Spacer()
}
.frame(width: UIScreen.main.bounds.width - 20, height: 200)
.background(
holiday.cityImage
.resizable()
.aspectRatio(contentMode: .fill)
)
.cornerRadius(10)
.padding(10)
.padding(.top, 30)
.shadow(color: Color.gray, radius: 6, x: 3, y: 6)
}
HolidayDetails
struct HolidayDetails: View {
var holiday: Holiday
#State var moreDescription = false
var body: some View {
ScrollView {
VStack {
ZStack(alignment: .bottomLeading) {
holiday.cityImage
.resizable()
.frame(height: moreDescription ? UIScreen.main.bounds.height * 0.3 : UIScreen.main.bounds.height * 0.6)
.aspectRatio(contentMode: .fill)
.frame(width: UIScreen.main.bounds.width)
.animation(.easeInOut)
HStack {
VStack(alignment: .leading, spacing: 12) {
holiday.weatherImage
.resizable()
.frame(width: 64, height: 64)
VStack(alignment: .leading, spacing: 0) {
Text("\(holiday.city),")
.font(.largeTitle)
.fontWeight(.bold)
Text(holiday.country)
.font(.title)
}
Text("\(holiday.season.rawValue) · \(holiday.duration) days")
.font(.headline)
.fontWeight(.light)
}
.foregroundColor(Color.white)
.animation(.easeInOut)
.padding()
}
}
VStack(alignment: .center, spacing: 12) {
Text(holiday.description)
.font(moreDescription ? .subheadline : .caption)
.lineLimit(moreDescription ? 99 : 2)
.opacity(moreDescription ? 1 : 0.5)
.animation(.easeInOut)
.padding()
Button(action: {
withAnimation(.easeInOut(duration: 3)) {
self.moreDescription.toggle()
}
}) {
Text(moreDescription ? "Less.." : "More..")
.font(.caption)
.padding(.vertical, moreDescription ? 10 : 5)
.padding(.horizontal, moreDescription ? 30 : 15)
.background(Color.blue)
.foregroundColor(Color.white)
.animation(.easeInOut)
}
.cornerRadius(10)
}
Spacer()
}
}
}
}
Holiday model
import Foundation
import SwiftUI
struct Holiday: Hashable, Codable, Identifiable {
var id: Int
var city: String
var country: String
var description: String
var duration: Int
var weather: Weather
var season: Season
}
extension Holiday {
var weatherImage: Image {
Image("\(self.weather)")
}
var cityImage: Image {
Image(self.city
.replacingOccurrences(of: " ", with: "")
.lowercased())
}
}
enum Weather: String, CaseIterable, Hashable, Codable {
case cloudy = "cloudy"
case rainy = "rainy"
case snowy = "snowy"
case sunny = "sunny"
}
enum Season: String, CaseIterable, Hashable, Codable {
case summer = "Summer"
case winter = "Winter"
case spring = "Spring"
case autumn = "Autumn"
}
And this is how I get holiday populated
import Foundation
let holidayData: [Holiday] = load("holidayData.json")
func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
Without the Navigation link the background image and the weather image are visible.
Try to put .renderingMode(.original) in your Image
Try to add this parameter to your NaviguationLink or Button
.buttonStyle(PlainButtonStyle())
How can I animate Tabbar Items (of a TabView) on selection in SwiftUI?
for example give the selected item a .scaleEffect() with .spring() animation
or sth like below:
This is what I've tried so far:
struct MyTabbedView: View {
#State var enlargeIt1 = false
#State var enlargeIt2 = true
var body: some View {
TabView {
Text("Item 1")
.onAppear {
self.enlargeIt1.toggle()
self.enlargeIt2.toggle()
}
.tabItem{
VStack{
Image(systemName: "music.note")
.font(self.enlargeIt1 ? .system(size: 30) : .system(size: 15) )
.animation(.interpolatingSpring(mass: 0.7, stiffness: 200, damping: 10, initialVelocity: 4))
Text("Music")
}
}.tag(1)
Text("Item 2")
.onAppear {
self.enlargeIt1.toggle()
self.enlargeIt2.toggle()
}
.tabItem{
VStack{
Image(systemName: "music.mic")
.font(self.enlargeIt2 ? .system(size: 30) : .system(size: 15) )
.animation(.interpolatingSpring(mass: 0.7, stiffness: 200, damping: 10, initialVelocity: 4))
Text("Mic")
}
}.tag(2)
}
}
}
and the result is this:
I tried approximately the same code in a separate View called TestView :
struct TestView: View {
#State var enlargeIt1 : Bool = false
var body: some View {
VStack{
Image(systemName: "music.note")
.font(self.enlargeIt1 ? .system(size: 30) : .system(size: 15) )
.animation(.interpolatingSpring(mass: 0.7, stiffness: 200, damping: 10, initialVelocity: 4))
Text("Music")
}
.onTapGesture {
self.enlargeIt1.toggle()
}
}
}
and this is the result:
What's wrong with the TabView I've created that it's not giving the same result?
Here is possible approach for standard TabView (for provided code snapshot).
The idea is to use animatable modifier for font size over used SF images.
Tested with Xcode 11.4 / iOS 13.4
// Animating font size
struct AnimatableSFImage: AnimatableModifier {
var size: CGFloat
var animatableData: CGFloat {
get { size }
set { size = newValue }
}
func body(content: Self.Content) -> some View {
content
.font(.system(size: size))
}
}
// helper extension
extension Image {
func animatingSF(size: CGFloat) -> some View {
self.modifier(AnimatableSFImage(size: size))
}
}
// Modified test code snapshot
struct TestAnimatedTabBar: View {
#State var enlargeIt1 = false
#State var enlargeIt2 = true
var body: some View {
TabView {
Text("Item 1")
.onAppear {
self.enlargeIt1.toggle()
self.enlargeIt2.toggle()
}
.tabItem{
VStack{
Image(systemName: "music.note")
.animatingSF(size: self.enlargeIt1 ? 30 : 15 )
Text("Music")
}.animation(.interpolatingSpring(mass: 0.7,
stiffness: 200, damping: 10, initialVelocity: 4))
}.tag(1)
Text("Item 2")
.onAppear {
self.enlargeIt1.toggle()
self.enlargeIt2.toggle()
}
.tabItem{
VStack{
Image(systemName: "music.mic")
.animatingSF(size: self.enlargeIt2 ? 30 : 15 )
Text("Mic")
}.animation(.interpolatingSpring(mass: 0.7,
stiffness: 200, damping: 10, initialVelocity: 4))
}.tag(2)
}
}
}
Someone created a custom TabView that might be of help to you. I'm sure you could modify it to suit your needs.
BottomBar component for SwiftUI inspired by this concept
https://github.com/smartvipere75/bottombar-swiftui
import SwiftUI
import BottomBar_SwiftUI
let items: [BottomBarItem] = [
BottomBarItem(icon: "house.fill", title: "Home", color: .purple),
BottomBarItem(icon: "heart", title: "Likes", color: .pink),
BottomBarItem(icon: "magnifyingglass", title: "Search", color: .orange),
BottomBarItem(icon: "person.fill", title: "Profile", color: .blue)
]
struct BasicView: View {
let item: BottomBarItem
var detailText: String {
"\(item.title) Detail"
}
var followButton: some View {
Button(action: openTwitter) {
VStack {
Text("Developed by Bezhan Odinaev")
.font(.headline)
.color(item.color)
Text("#smartvipere75")
.font(.subheadline)
.foregroundColor(.gray)
}
}
}
var destination: some View {
Text(detailText)
.navigationBarTitle(Text(detailText))
}
var navigateButton: some View {
NavigationLink(destination: destination) {
ZStack {
Rectangle()
.fill(item.color)
.cornerRadius(8)
.frame(height: 52)
.padding(.horizontal)
Text("Navigate")
.font(.headline)
.foregroundColor(.white)
}
}
}
func openTwitter() {
guard let url = URL(string: "https://twitter.com/smartvipere75") else {
return
}
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
var body: some View {
VStack {
Spacer()
followButton
Spacer()
navigateButton
}
}
}
struct ContentView : View {
#State private var selectedIndex: Int = 0
var selectedItem: BottomBarItem {
items[selectedIndex]
}
var body: some View {
NavigationView {
VStack {
BasicView(item: selectedItem)
.navigationBarTitle(Text(selectedItem.title))
BottomBar(selectedIndex: $selectedIndex, items: items)
}
}
}
}
Problem
How can I modify the scroll target of a scrollView? I am looking for kind of a replacement for the "classic" scrollView delegate method
override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
...where we can modfify the targeted scrollView.contentOffset via targetContentOffset.pointee for instance to create a custom paging behaviour.
Or in other words: I do want to create a paging effect in a (horizontal) scrollView.
What I have tried ie. is something like this:
ScrollView(.horizontal, showsIndicators: true, content: {
HStack(alignment: VerticalAlignment.top, spacing: 0, content: {
card(title: "1")
card(title: "2")
card(title: "3")
card(title: "4")
})
})
// 3.
.content.offset(x: self.dragState.isDragging == true ? self.originalOffset : self.modifiedOffset, y: 0)
// 4.
.animation(self.dragState.isDragging == true ? nil : Animation.spring())
// 5.
.gesture(horizontalDragGest)
Attempt
This is what I tried (besides a custom scrollView approach):
A scrollView has a content area larger then screen space to enable scrolling at all.
I created a DragGesture() to detect if there is a drag going on. In the .onChanged and .onEnded closures I modified my #State values to create a desired scrollTarget.
Conditionally fed in both the original unchanged and the new modified values into the .content.offset(x: y:) modifier - depending on the dragState as a replacement for missing scrollDelegate methods.
Added animation acting conditionally only when drag has ended.
Attached the gesture to the scrollView.
Long story short. It doesn't work.
I hope I got across what my problem is.
Any solutions out there? Looking forward to any input. Thanks!
I have managed to achieve a paging behaviour with a #Binding index. The solution might look dirty, I'll explain my workarounds.
The first thing I got wrong, was to get alignment to .leading instead of the default .center, otherwise the offset works unusual. Then I combined the binding and a local offset state. This kinda goes against the "Single source of truth" principle, but otherwise I had no idea how to handle external index changes and modify my offset.
So, my code is the following
struct SwiftUIPagerView<Content: View & Identifiable>: View {
#Binding var index: Int
#State private var offset: CGFloat = 0
#State private var isGestureActive: Bool = false
// 1
var pages: [Content]
var body: some View {
GeometryReader { geometry in
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center, spacing: 0) {
ForEach(self.pages) { page in
page
.frame(width: geometry.size.width, height: nil)
}
}
}
// 2
.content.offset(x: self.isGestureActive ? self.offset : -geometry.size.width * CGFloat(self.index))
// 3
.frame(width: geometry.size.width, height: nil, alignment: .leading)
.gesture(DragGesture().onChanged({ value in
// 4
self.isGestureActive = true
// 5
self.offset = value.translation.width + -geometry.size.width * CGFloat(self.index)
}).onEnded({ value in
if -value.predictedEndTranslation.width > geometry.size.width / 2, self.index < self.pages.endIndex - 1 {
self.index += 1
}
if value.predictedEndTranslation.width > geometry.size.width / 2, self.index > 0 {
self.index -= 1
}
// 6
withAnimation { self.offset = -geometry.size.width * CGFloat(self.index) }
// 7
DispatchQueue.main.async { self.isGestureActive = false }
}))
}
}
}
you may just wrap your content, I used it for "Tutorial Views".
this a trick to switch between external and internal state changes
.leading is mandatory if you don't want to translate all offsets to center.
set the state to local state change
calculate the full offset from the gesture delta (*-1) plus the previous index state
at the end set the final index based on the gesture predicted end, while rounding the offset up or down
reset the state to handle external changes to index
I have tested it in the following context
struct WrapperView: View {
#State var index: Int = 0
var body: some View {
VStack {
SwiftUIPagerView(index: $index, pages: (0..<4).map { index in TODOView(extraInfo: "\(index + 1)") })
Picker(selection: self.$index.animation(.easeInOut), label: Text("")) {
ForEach(0..<4) { page in Text("\(page + 1)").tag(page) }
}
.pickerStyle(SegmentedPickerStyle())
.padding()
}
}
}
where TODOView is my custom view that indicates a view to implement.
I hope I get the question right, if not please specify which part should I focus on. Also I welcome any suggestions to remove the isGestureActive state.
#gujci your solution is perfect, for more general usage, make it accept Models and view builder as in (note the I pass the geometry size in the builder) :
struct SwiftUIPagerView<TModel: Identifiable ,TView: View >: View {
#Binding var index: Int
#State private var offset: CGFloat = 0
#State private var isGestureActive: Bool = false
// 1
var pages: [TModel]
var builder : (CGSize, TModel) -> TView
var body: some View {
GeometryReader { geometry in
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center, spacing: 0) {
ForEach(self.pages) { page in
self.builder(geometry.size, page)
}
}
}
// 2
.content.offset(x: self.isGestureActive ? self.offset : -geometry.size.width * CGFloat(self.index))
// 3
.frame(width: geometry.size.width, height: nil, alignment: .leading)
.gesture(DragGesture().onChanged({ value in
// 4
self.isGestureActive = true
// 5
self.offset = value.translation.width + -geometry.size.width * CGFloat(self.index)
}).onEnded({ value in
if -value.predictedEndTranslation.width > geometry.size.width / 2, self.index < self.pages.endIndex - 1 {
self.index += 1
}
if value.predictedEndTranslation.width > geometry.size.width / 2, self.index > 0 {
self.index -= 1
}
// 6
withAnimation { self.offset = -geometry.size.width * CGFloat(self.index) }
// 7
DispatchQueue.main.async { self.isGestureActive = false }
}))
}
}
}
and can be used as :
struct WrapperView: View {
#State var index: Int = 0
#State var items : [(color:Color,name:String)] = [
(.red,"Red"),
(.green,"Green"),
(.yellow,"Yellow"),
(.blue,"Blue")
]
var body: some View {
VStack(spacing: 0) {
SwiftUIPagerView(index: $index, pages: self.items.identify { $0.name }) { size, item in
TODOView(extraInfo: item.model.name)
.frame(width: size.width, height: size.height)
.background(item.model.color)
}
Picker(selection: self.$index.animation(.easeInOut), label: Text("")) {
ForEach(0..<4) { page in Text("\(page + 1)").tag(page) }
}
.pickerStyle(SegmentedPickerStyle())
}.edgesIgnoringSafeArea(.all)
}
}
with the help of some utilities :
struct MakeIdentifiable<TModel,TID:Hashable> : Identifiable {
var id : TID {
return idetifier(model)
}
let model : TModel
let idetifier : (TModel) -> TID
}
extension Array {
func identify<TID: Hashable>(by: #escaping (Element)->TID) -> [MakeIdentifiable<Element, TID>]
{
return self.map { MakeIdentifiable.init(model: $0, idetifier: by) }
}
}
#gujci, thank you for interesting example. I've played with it and removed the isGestureActive state. Full example may be found in my gist.
struct SwiftUIPagerView<Content: View & Identifiable>: View {
#State private var index: Int = 0
#State private var offset: CGFloat = 0
var pages: [Content]
var body: some View {
GeometryReader { geometry in
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center, spacing: 0) {
ForEach(self.pages) { page in
page
.frame(width: geometry.size.width, height: nil)
}
}
}
.content.offset(x: self.offset)
.frame(width: geometry.size.width, height: nil, alignment: .leading)
.gesture(DragGesture()
.onChanged({ value in
self.offset = value.translation.width - geometry.size.width * CGFloat(self.index)
})
.onEnded({ value in
if abs(value.predictedEndTranslation.width) >= geometry.size.width / 2 {
var nextIndex: Int = (value.predictedEndTranslation.width < 0) ? 1 : -1
nextIndex += self.index
self.index = nextIndex.keepIndexInRange(min: 0, max: self.pages.endIndex - 1)
}
withAnimation { self.offset = -geometry.size.width * CGFloat(self.index) }
})
)
}
}
}
As far as I know scrolls in swiftUI doesn't support anything potentially useful such as scrollViewDidScroll or scrollViewWillEndDragging yet. I suggest using either classic UIKit views for making very custom behavior and cool SwiftUI views for anything that is easier. I've tried that a lot and it actually works! Have a look at this guide. Hope that helps
Alternative solution would be to integrate UIKit into SwiftUI using UIViewRepresentative which links UIKit components with SwiftUI. For additional leads and resources, see how Apple suggests you interface with UIKit: Interfacing with UIKit. They have a good example that shows to page between images and track selection index.
Edit: Until they (Apple) implement some sort of content offset that effects the scroll instead of the entire view, this is their suggested solution since they knew the initial release of SwiftUI wouldn't encompass all functionality of UIKit.
Details
Xcode 14
Swift 5.6.1
Requirements
I do not want to use integration with UIKit (clean SwiftUI ONLY)
I do not want to scroll to the any "ID", I want to scroll to the point
Solution
import SwiftUI
#available(iOS 14.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
struct ExtendedScrollView<Content>: View where Content: View {
private let contentProvider: _AligningContentProvider<Content>
// Main Idea from: https://github.com/edudnyk/SolidScroll/blob/main/Sources/SolidScroll/ScrollView.swift
private var config: _ScrollViewConfig
init(config: _ScrollViewConfig = _ScrollViewConfig(),
#ViewBuilder content: () -> Content) {
contentProvider = _AligningContentProvider(content: content(), horizontal: .center, vertical: .center)
self.config = config
}
init(_ axes: Axis.Set = .vertical,
showsIndicators: Bool = true,
#ViewBuilder content: () -> Content) {
var config = _ScrollViewConfig()
config.showsHorizontalIndicator = axes.contains(.horizontal) && showsIndicators
config.showsVerticalIndicator = axes.contains(.vertical) && showsIndicators
self.init(config: config, content: content)
}
init(config: () -> _ScrollViewConfig,
#ViewBuilder content: () -> Content) {
self.init(config: config(), content: content)
}
var body: some View {
_ScrollView(contentProvider: contentProvider, config: config)
}
}
extension _ContainedScrollViewKey: PreferenceKey {}
// MARK: Track ScrollView Scrolling
struct TrackableExtendedScrollView: ViewModifier {
let onChange: (_ScrollViewProxy?) -> Void
func body(content: Content) -> some View {
content
.onPreferenceChange(_ContainedScrollViewKey.self, perform: onChange)
}
}
extension View {
func onScrollChange(perform: #escaping (_ScrollViewProxy?) -> Void) -> some View {
modifier(TrackableExtendedScrollView(onChange: perform))
}
}
Usage Sample
private var gridItemLayout = (0..<40).map { _ in
GridItem(.fixed(50), spacing: 0, alignment: .leading)
}
// ....
ExtendedScrollView() {
LazyHGrid(rows: gridItemLayout) {
ForEach((0..<numberOfRows*numberOfColumns), id: \.self) { index in
let color = (index/numberOfRows)%2 == 0 ? Color(0x94D2BD) : Color(0xE9D8A6)
Text("\(index)")
.frame(width: 50)
.frame(maxHeight: .infinity)
}
}
}
.onScrollChange { proxy in
// let offset = proxy?.contentOffset.y
}
Full Sample
Implementation details
First column and first row are always on the screen
There are 3 "CollectionView":
first row "CollectionView"
first column "CollectionView"
main content "CollectionView"
All "CollectionView" are synced (if you scroll one "CollectionView", another will also be scrolled)
Do not forget to paste The Solution code here
import SwiftUI
import Combine
struct ContentView: View {
private let columWidth: CGFloat = 50
private var gridItemLayout0 = [GridItem(.fixed(50), spacing: 0, alignment: .leading)]
private var gridItemLayout1 = [GridItem(.fixed(50), spacing: 0, alignment: .leading)]
private var gridItemLayout = (0..<40).map { _ in
GridItem(.fixed(50), spacing: 0, alignment: .leading)
}
#State var text: String = "scrolling not detected"
#State private var scrollViewProxy1: _ScrollViewProxy?
#State private var tableContentScrollViewProxy: _ScrollViewProxy?
#State private var tableHeaderScrollViewProxy: _ScrollViewProxy?
private let numberOfColumns = 50
private let numberOfRows = 40
let headerColor = Color(0xEE9B00)
let firstColumnColor = Color(0x0A9396)
let headerTextColor = Color(.white)
let horizontalSpacing: CGFloat = 6
let verticalSpacing: CGFloat = 0
let firstColumnWidth: CGFloat = 100
let columnWidth: CGFloat = 60
var body: some View {
VStack(spacing: 0) {
Text("First column and row are sticked to the content")
.foregroundColor(.gray)
Text(text)
HStack {
Rectangle()
.frame(width: firstColumnWidth-2)
.foregroundColor(.clear)
buildFirstCollectionViewRow()
}
.frame(height: 50)
HStack(alignment: .firstTextBaseline, spacing: horizontalSpacing) {
buildFirstCollectionViewColumn()
buildCollectionViewContent()
}
}
}
#ViewBuilder
private func buildFirstCollectionViewRow() -> some View {
ExtendedScrollView() {
LazyHGrid(rows: gridItemLayout1, spacing: horizontalSpacing) {
ForEach((0..<numberOfColumns), id: \.self) {
let color = $0%2 == 0 ? Color(0x005F73) : Color(0xCA6702)
Text("Value\($0)")
.frame(width: columnWidth)
.frame(maxHeight: .infinity)
.foregroundColor(headerTextColor)
.background(color)
.font(.system(size: 16, weight: .semibold))
}
}
}
.onScrollChange { proxy in
if tableHeaderScrollViewProxy != proxy { tableHeaderScrollViewProxy = proxy }
guard proxy?.isScrolling ?? false else { return }
if tableHeaderScrollViewProxy?.contentOffset.x != tableContentScrollViewProxy?.contentOffset.x,
let offset = proxy?.contentOffset.x {
tableContentScrollViewProxy?.contentOffset.x = offset
}
text = "scrolling: header"
}
}
}
// MARK: Collection View Elements
extension ContentView {
#ViewBuilder
private func buildFirstCollectionViewColumn() -> some View {
ExtendedScrollView() {
LazyHGrid(rows: gridItemLayout, spacing: horizontalSpacing) {
ForEach((0..<numberOfRows), id: \.self) {
Text("multi line text \($0)")
.foregroundColor(.white)
.lineLimit(2)
.frame(width: firstColumnWidth)
.font(.system(size: 16, weight: .semibold))
.frame(maxHeight: .infinity)
.background(firstColumnColor)
.border(.white)
}
}
}
.frame(width: firstColumnWidth)
.onScrollChange { proxy in
if scrollViewProxy1 != proxy { scrollViewProxy1 = proxy }
guard proxy?.isScrolling ?? false else { return }
if scrollViewProxy1?.contentOffset.y != tableContentScrollViewProxy?.contentOffset.y,
let offset = proxy?.contentOffset.y {
tableContentScrollViewProxy?.contentOffset.y = offset
}
text = "scrolling: 1st column"
}
}
#ViewBuilder
private func buildCollectionViewContent() -> some View {
ExtendedScrollView() {
LazyHGrid(rows: gridItemLayout, spacing: horizontalSpacing) {
ForEach((0..<numberOfRows*numberOfColumns), id: \.self) { index in
let color = (index/numberOfRows)%2 == 0 ? Color(0x94D2BD) : Color(0xE9D8A6)
Text("\(index)")
.frame(width: columnWidth)
.frame(maxHeight: .infinity)
.background(color)
.border(.white)
}
}
}
.onScrollChange { proxy in
if tableContentScrollViewProxy != proxy { tableContentScrollViewProxy = proxy }
guard proxy?.isScrolling ?? false else { return }
if scrollViewProxy1?.contentOffset.y != tableContentScrollViewProxy?.contentOffset.y,
let offset = proxy?.contentOffset.y {
self.scrollViewProxy1?.contentOffset.y = offset
}
if tableHeaderScrollViewProxy?.contentOffset.x != tableContentScrollViewProxy?.contentOffset.x,
let offset = proxy?.contentOffset.x {
self.tableHeaderScrollViewProxy?.contentOffset.x = offset
}
text = "scrolling: content"
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
extension Color {
init(_ hex: UInt, alpha: Double = 1) {
self.init(
.sRGB,
red: Double((hex >> 16) & 0xFF) / 255,
green: Double((hex >> 8) & 0xFF) / 255,
blue: Double(hex & 0xFF) / 255,
opacity: alpha
)
}
}
Full Sample Demo