Nested ScrollView SwiftUI - scrollview

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

Related

SwiftUI: How to manage dynamic rows/columns of Views?

I am finding my first SwiftUI challenge to be a tricky one. Given a set of playing cards, display them in a way that allows the user to see the full deck while using space efficiently. Here's a simplified example:
In this case 52 cards (Views) are presented, in order of 01 - 52. They are dynamically packed into the parent view such that there is enough spacing between them to allow the numbers to be visible.
The problem
If we change the shape of the window, the packing algorithm will pack them (correctly) into a different number of rows & columns. However, when the number of rows/columns change, the card Views are out of order (some are duplicated):
In the image above, notice how the top row is correct (01 - 26) but the second row starts at 12 and ends at 52. I expect his is because the second row originally contained 12 - 22 and those views were not updated.
Additional criteria: The number of cards and the order of those cards can change at runtime. Also, this app must be able to be run on Mac, where the window size can be dynamically adjusted to any shape (within reason.)
I understand that when using ForEach for indexing, one must use a constant but I must loop through a series of rows and columns, each of which can change. I have tried adding id: \.self, but this did not solve the problem. I ended up looping through the maximum possible number of rows/columns (to keep the loop constant) and simply skipped the indices that I didn't want. This is clearly wrong.
The other alternative would be to use arrays of Identifiable structures. I tried this, but wasn't able to figure out how to organize the data flow. Also, since the packing is dependent on the size of the parent View it would seem that the packing must be done inside the parent. How can the parent generate the data needed to fulfill the deterministic requirements of SwiftUI?
I'm willing to do the work to get this working, any help understanding how I should proceed would be greatly appreciated.
The code below is a fully working, simplified version. Sorry if it's still a bit large. I'm guessing the problem revolves around the use of the two ForEach loops (which are, admittedly, a bit janky.)
import SwiftUI
// This is a hacked together simplfied view of a card that meets all requirements for demonstration purposes
struct CardView: View {
public static let kVerticalCornerExposureRatio: CGFloat = 0.237
public static let kPhysicalAspect: CGFloat = 63.5 / 88.9
#State var faceCode: String
func bgColor(_ faceCode: String) -> Color {
let ascii = Character(String(faceCode.suffix(1))).asciiValue!
let r = (CGFloat(ascii) / 3).truncatingRemainder(dividingBy: 0.7)
let g = (CGFloat(ascii) / 17).truncatingRemainder(dividingBy: 0.9)
let b = (CGFloat(ascii) / 23).truncatingRemainder(dividingBy: 0.6)
return Color(.sRGB, red: r, green: g, blue: b, opacity: 1)
}
var body: some View {
GeometryReader { geometry in
RoundedRectangle(cornerRadius: 10)
.fill(bgColor(faceCode))
.cornerRadius(8)
.frame(width: geometry.size.height * CardView.kPhysicalAspect, height: geometry.size.height)
.aspectRatio(CardView.kPhysicalAspect, contentMode: .fit)
.overlay(Text(faceCode)
.font(.system(size: geometry.size.height * 0.1))
.padding(5)
, alignment: .topLeading)
.overlay(RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 2))
}
}
}
// A single rows of our fanned out cards
struct RowView: View {
var cards: [String]
var width: CGFloat
var height: CGFloat
var start: Int
var columns: Int
var cardWidth: CGFloat {
return height * CardView.kPhysicalAspect
}
var cardSpacing: CGFloat {
return (width - cardWidth) / CGFloat(columns - 1)
}
var body: some View {
HStack(spacing: 0) {
// Visit all cards, but only add the ones that are within the range defined by start/columns
ForEach(0 ..< cards.count) { index in
if index < columns && start + index < cards.count {
HStack(spacing: 0) {
CardView(faceCode: cards[start + index])
.frame(width: cardWidth, height: height)
}
.frame(width: cardSpacing, alignment: .leading)
}
}
}
}
}
struct ContentView: View {
#State var cards: [String]
#State var fanned: Bool = true
// Generates the number of rows/columns that meets our rectangle-packing criteria
func pack(area: CGSize, count: Int) -> (rows: Int, cols: Int) {
let areaAspect = area.width / area.height
let exposureAspect = 1 - CardView.kVerticalCornerExposureRatio
let aspect = areaAspect / CardView.kPhysicalAspect * exposureAspect
var rows = Int(ceil(sqrt(Double(count)) / aspect))
let cols = count / rows + (count % rows > 0 ? 1 : 0)
while cols * (rows - 1) >= count { rows -= 1 }
return (rows, cols)
}
// Calculate the height of a card such that a series of rows overlap without covering the corner pips
func cardHeight(frameHeight: CGFloat, rows: Int) -> CGFloat {
let partials = CGFloat(rows - 1) * CardView.kVerticalCornerExposureRatio + 1
return frameHeight / partials
}
var body: some View {
VStack {
GeometryReader { geometry in
let w = geometry.size.width
let h = geometry.size.height
if w > 0 && h > 0 { // using `geometry.size != .zero` crashes the preview :(
let (rows, cols) = pack(area: geometry.size, count: cards.count)
let cardHeight = cardHeight(frameHeight: h, rows: rows)
let rowSpacing = cardHeight * CardView.kVerticalCornerExposureRatio
VStack(spacing: 0) {
// Visit all cards as if the layout is one row per card and simply skip the rows
// we're not interested in. If I make this `0 ..< rows` - it doesn't work at all
ForEach(0 ..< cards.count) { row in
if row < rows {
RowView(cards: cards, width: w, height: cardHeight, start: row * cols, columns: cols)
.frame(width: w, height: rowSpacing, alignment: .topLeading)
}
}
}
.frame(width: w, height: 100, alignment: .topLeading)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(cards: ["01", "02", "03", "04", "05", "06", "07", "08", "09",
"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"])
.background(Color.white)
.preferredColorScheme(.light)
}
}
I think you're on the right track that you need to use an Identifiable to prevent the system from making assumptions about what can be recycled in the ForEach. To that end, I've created a Card:
struct Card : Identifiable {
let id = UUID()
var title : String
}
Within the RowView, this is trivial to use:
struct RowView: View {
var cards: [Card]
var width: CGFloat
var height: CGFloat
var columns: Int
var cardWidth: CGFloat {
return height * CardView.kPhysicalAspect
}
var cardSpacing: CGFloat {
return (width - cardWidth) / CGFloat(columns - 1)
}
var body: some View {
HStack(spacing: 0) {
// Visit all cards, but only add the ones that are within the range defined by start/columns
ForEach(cards) { card in
HStack(spacing: 0) {
CardView(faceCode: card.title)
.frame(width: cardWidth, height: height)
}
.frame(width: cardSpacing, alignment: .leading)
}
}
}
}
In the ContentView, things get a little more complicated because of the dynamic rows:
struct ContentView: View {
#State var cards: [Card] = (1..<53).map { Card(title: "\($0)") }
#State var fanned: Bool = true
// Generates the number of rows/columns that meets our rectangle-packing criteria
func pack(area: CGSize, count: Int) -> (rows: Int, cols: Int) {
let areaAspect = area.width / area.height
let exposureAspect = 1 - CardView.kVerticalCornerExposureRatio
let aspect = areaAspect / CardView.kPhysicalAspect * exposureAspect
var rows = Int(ceil(sqrt(Double(count)) / aspect))
let cols = count / rows + (count % rows > 0 ? 1 : 0)
while cols * (rows - 1) >= count { rows -= 1 }
return (rows, cols)
}
// Calculate the height of a card such that a series of rows overlap without covering the corner pips
func cardHeight(frameHeight: CGFloat, rows: Int) -> CGFloat {
let partials = CGFloat(rows - 1) * CardView.kVerticalCornerExposureRatio + 1
return frameHeight / partials
}
var body: some View {
VStack {
GeometryReader { geometry in
let w = geometry.size.width
let h = geometry.size.height
if w > 0 && h > 0 { // using `geometry.size != .zero` crashes the preview :(
let (rows, cols) = pack(area: geometry.size, count: cards.count)
let cardHeight = cardHeight(frameHeight: h, rows: rows)
let rowSpacing = cardHeight * CardView.kVerticalCornerExposureRatio
VStack(spacing: 0) {
ForEach(Array(cards.enumerated()), id: \.1.id) { (index, card) in
let row = index / cols
if index % cols == 0 {
let rangeMin = min(cards.count, row * cols)
let rangeMax = min(cards.count, rangeMin + cols)
RowView(cards: Array(cards[rangeMin..<rangeMax]), width: w, height: cardHeight, columns: cols)
.frame(width: w, height: rowSpacing, alignment: .topLeading)
}
}
}
.frame(width: w, height: 100, alignment: .topLeading)
}
}
}
}
}
This loops through all of the cards and uses the unique IDs. Then, there's some logic to use the index to determine what row the loop is on and if it is the beginning of the loop (and thus should render the row). Finally, it sends just a subset of the cards to the RowView.
Note: you can look at Swift Algorithms for a more efficient method than enumerated. See indexed: https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md
#jnpdx has provided a valid answer that is direct in its approach, which helps to understand the problem without adding additional complexity.
I have also stumbled across an alternative approach that requires more drastic changes to the structure of the code, but is more performant while also leading to more production-ready code.
To begin with, I created a CardData struct that implements the ObservableObject protocol. This includes the code to pack a set of cards into rows/columns based on a given CGSize.
class CardData: ObservableObject {
var cards = [[String]]()
var hasData: Bool {
return cards.count > 0 && cards[0].count > 0
}
func layout(cards: [String], size: CGSize) -> CardData {
// ...
// Populate `cards` with packed rows/columns
// ...
return self
}
}
This would only work if the layout code could know the frame size for which it was packing. To that end, I used .onChange(of:perform:) to track changes to the geometry itself:
.onChange(of: geometry.size, perform: { size in
cards.layout(cards: cardStrings, size: size)
})
This greatly simplifies the ContentView:
var body: some View {
VStack {
GeometryReader { geometry in
let cardHeight = cardHeight(frameHeight: geometry.size.height, rows: cards.rows)
let rowSpacing = cardHeight * CardView.kVerticalCornerExposureRatio
VStack(spacing: 0) {
ForEach(cards.cards, id: \.self) { row in
RowView(cards: row, width: geometry.size.width, height: cardHeight)
.frame(width: geometry.size.width, height: rowSpacing, alignment: .topLeading)
}
}
.frame(width: geometry.size.width, height: 100, alignment: .topLeading)
.onChange(of: geometry.size, perform: { size in
_ = cards.layout(cards: CardData.faceCodes, size: size)
})
}
}
}
In addition, it also simplifies the RowView:
var body: some View {
HStack(spacing: 0) {
ForEach(cards, id: \.self) { card in
HStack(spacing: 0) {
CardView(faceCode: card)
.frame(width: cardWidth, height: height)
}
.frame(width: cardSpacing, alignment: .leading)
}
}
}
Further improvements can be had by storing rows/columns of CardViews inside CardData rather than the card title strings. This will eliminate the need to recreate a full set of (in my case, complex) CardViews in the View code.
The final end result now looks like this:

SwiftUI - Change opacity of a view based on position of scrollview

This is more of a "is it possible" question.
I currently have a floating custom navigation bar that sits in its own parent container with a white background and an opacity of 0%. I'd like to change the opacity of that parent container from 0% to 50% after the scrollView has scrolled past the hero image in the scrollview.
var body: some View {
ZStack {
ScrollView(.vertical, showsIndicators: false) {
GeometryReader { geometry in
ZStack{
if geometry.frame(in: .global).minY <= 0 {
Image(self.venueImage)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: geometry.size.width, height: geometry.size.height)
.offset(y: geometry.frame(in: .global).minY/9)
.clipped()
} else {
Image(self.venueImage)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: geometry.size.width, height: geometry.size.height + geometry.frame(in: .global).minY)
.clipped()
.offset(y: -geometry.frame(in: .global).minY)
}
}
}.frame(height: 300)
VStack {
HStack {
Text(self.title)
.font(.title)
.fontWeight(.bold)
Spacer()
}.padding(.horizontal, 24)
HStack {
Text(self.venueArea)
.foregroundColor(Color("bodyText"))
Spacer()
}.padding(.horizontal, 24)
VStack {
ForEach(self.venueProd) { gc in
VStack {
HStack {
Text(gc.title)
.font(.system(size: 17))
.fontWeight(.semibold)
Spacer()
}
HStack {
Text(gc.productDescription)
.foregroundColor(Color("bodyText"))
.font(.system(size: 15))
.padding(.top, 5)
Spacer()
}
HStack {
Text("$\(gc.productPrice, specifier: "%.2f")")
Spacer()
}.padding(.top, 8)
Divider()
}.padding(.bottom, 8)
}
Spacer()
}.padding(.horizontal, 24)
.padding(.top, 24)
.padding(.bottom, 60)
Spacer()
}
}.edgesIgnoringSafeArea(.top)
// AREA I'M TRYING TO MODIFY OPACITY ON SCROLL
ZStack {
GeometryReader { geometry in
ZStack {
VStack {
Text("")
.frame(width: geometry.size.width, height: 120)
.background(Color.white)
.opacity(0.3 )
Spacer()
}
}.edgesIgnoringSafeArea(.top) // Ends ZStack
} // Ends Geometry Reader
VStack {
GeometryReader { gr in
HStack {
Button(action: {self.presentationMode.wrappedValue.dismiss()}) {
Image(systemName: "chevron.left")
.foregroundColor(.black)
.padding(.leading, 16)
HStack {
Text("Venues · Venue Details")
.font(.system(size: 15))
.fontWeight(.bold)
.foregroundColor(Color.black)
.padding()
Spacer()
}
}.frame(width: gr.size.width * 0.92, height: 48)
.background(Color.white)
.cornerRadius(8)
}.padding(.leading, 16)
Spacer()
}
}
.padding(.top, 50)
.edgesIgnoringSafeArea(.top)
} // Ends Floating Menu ZStack
} // Second ZStack
}
}
Here is a demo of idea.
The code just shows the approach and due to simplicity it can be easily integrated/transferred. All background colors is just for better visibility, as well as calculation might be more complex and included animations, but the idea kept the same - it is possible to read rect of image in global coordinates using GeometryProxy and depending on that change opacity of some other view via corresponding #State.
struct TestScrollDependentOpacity: View {
#State private var barOpacity: Double = 0
var body: some View {
ZStack(alignment: .top) {
mainContent
floatingBar
}
}
private var mainContent: some View {
ScrollView {
GeometryReader { g -> AnyView in
let rect = g.frame(in: .global)
DispatchQueue.main.async {
self.barOpacity = rect.maxY < 0 ? 0.5 : 0.0
}
return AnyView(Image(systemName: "sun.max")
.resizable()
.aspectRatio(contentMode: .fit)
.position(x: g.size.width / 2.0, y: g.size.height / 2.0))
}
.frame(height: 100).background(Color.yellow)
VStack(alignment: .leading) {
ForEach (0..<40) { i in
HStack {
Text("Text \(i)").padding()
Spacer()
}
}
}.background(Color.green)
}
}
private var floatingBar: some View {
HStack {
Button("Left") { }
Spacer()
Button("Right") { }
}
.padding()
.background(Color.white.opacity(barOpacity))
.edgesIgnoringSafeArea(.top)
}
}

SwiftUI Images disappearing when in NavigationLink

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 to animate tabbar items (on selection) in SwiftUI?

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)
}
}
}
}

SwiftUI ScrollView: How to modify .content.offset aka Paging?

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