TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: How to use ScrollViewReader in two List(without button)?

Forums > SwiftUI

I have project, where two list of different banks show currency rate. And i want when I choose currency in first List, second List will have autoscrolling to the same currency. I saw tutorials with buttons, but it's not what I need. I thought use onTapGesture, but I can't realise how to involve it in right way. Thanks for help anyway.

My code:

import SwiftUI

struct ContentView: View {
    @State private var date = Date()
    @State var currenciesPB: [ExchangeRatesPB] = []
    @State var currenciesNBU: [ExchangeRatesNBU] = []

    @State var scrollToCurrency: String = ""
    @State var choosenCurrency: String = ""

    var body: some View {
        ZStack {
            Color(.systemGray6)
                .edgesIgnoringSafeArea(.all)
            VStack {
                HStack {
                    Spacer(minLength: 110)
                    Text("Курси валют")
                        .font(.title2)
                        .padding()

                    Spacer()
                    Image(systemName: "chart.bar.xaxis")
                        .font(.title)
                        .padding()
                }
                .foregroundColor(.white)
                .padding(.top)
                .background(Color.init(#colorLiteral(red: 0.4558259845, green: 0.5886077285, blue: 0.5515387654, alpha: 1)))
                .edgesIgnoringSafeArea(.top)

                //PB
                VStack {
                    HStack {
                        Text("ПриватБанк")
                            .foregroundColor(Color.init(#colorLiteral(red: 0.3549223542, green: 0.3776315749, blue: 0.4196012616, alpha: 1)))
                        Spacer(minLength: 70)

                        Image(systemName: "calendar")
                            .foregroundColor(.gray)
                        DatePicker("", selection: $date, displayedComponents: .date)
                    }
                    .font(.title2)
                    .padding(10)

                    HStack(spacing: 60) {
                        Text("Валюта")
                        Text("Купівля")
                        Text("Продаж")
                    } .foregroundColor(.gray)
                    VStack {
                        List(currenciesPB, id: \.self) { currencyPB in
                            VStack {
                                HStack(spacing: 60) {
                                    Text(currencyPB.ccy)
                                    Text(currencyPB.sale)
                                    Text(currencyPB.buy)
                                }
                                .onTapGesture {
                                    let value = currencyPB.ccy
                                    choosenCurrency = value
                                }
                                //.listRowBackground(Color(.systemGray6))
                                .foregroundColor(Color.init(#colorLiteral(red: 0.3549223542, green: 0.3776315749, blue: 0.4196012616, alpha: 1)))
                            }
                        }
                        .padding(.top)
                        .onAppear() {
                            ApiPB().getCurrency { (currenciesPB) in
                                self.currenciesPB = currenciesPB
                            }
                        }
                    }
                }

                //NBU
                VStack {
                    HStack {
                        Text("НБУ")
                            .foregroundColor(Color.init(#colorLiteral(red: 0.3549223542, green: 0.3776315749, blue: 0.4196012616, alpha: 1)))
                        Spacer(minLength: 150)

                        Image(systemName: "calendar")
                            .foregroundColor(.gray)
                        DatePicker("", selection: $date, displayedComponents: .date)
                    }
                    .font(.title2)
                    .padding(10)
                    ScrollViewReader { proxy in

                        VStack {
                            List(currenciesNBU, id: \.self) { currencyNBU in
                                VStack {
                                    HStack(spacing: 60) {
                                        Text(currencyNBU.txt)
                                        //Text(currencyNBU.cc)
                                        Spacer()
                                        Text(String(currencyNBU.rate))
                                    }
                                    .listRowBackground(Color(.systemGray6))
                                    .foregroundColor(Color.init(#colorLiteral(red: 0.3549223542, green: 0.3776315749, blue: 0.4196012616, alpha: 1)))
                                }
                            }

                            .padding(.top)
                            .onAppear() {
                                ApiNBU().getCurrency { (currenciesNBU) in
                                    self.currenciesNBU = currenciesNBU
                                }
                            }
                        }
                    }
                }
                //                Spacer()
            }
        }
    }
}

struct ExchangeRatesPB: Codable, Hashable {
    let ccy: String
    let base_ccy: String
    var buy: String
    var sale: String
}

class ApiPB {
    func getCurrency(completion: @escaping ([ExchangeRatesPB]) -> ()) {
        guard let url = URL(string: "https://api.privatbank.ua/p24api/pubinfo?json&exchange&coursid=5") else { return }

        URLSession.shared.dataTask(with: url) { (data, _, _) in
            let currenciesPB = try! JSONDecoder().decode([ExchangeRatesPB].self, from: data!)
            DispatchQueue.main.sync {
                completion(currenciesPB)
            }
        }
        .resume()
    }
}

struct ExchangeRatesNBU: Codable, Hashable {
    let r030: Int
    let txt: String
    var rate: Double
    var cc: String
}

class ApiNBU {
    func getCurrency(completion: @escaping ([ExchangeRatesNBU]) -> ()) {
        guard let url = URL(string: "https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?date=20200302&json") else { return }

        URLSession.shared.dataTask(with: url) { (data, _, _) in
            let currenciesNBU = try! JSONDecoder().decode([ExchangeRatesNBU].self, from: data!)
            DispatchQueue.main.sync {
                completion(currenciesNBU)
            }
        }
        .resume()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

2      

You need to figure out what is the criteria for determining where the bottom ScrollView should scroll to and then set that using code like in the following simple example:

struct Kid: Identifiable {
    let id = UUID()
    let name: String
    let family: [String]
}

struct ScrollToView: View {

    //just make a quickie array of stuff to put in our ScrollViews
    let kids: [Kid] = [
        Kid(name: "Charlotte",
            family: Array(repeating: ["Karen", "Sarah"], count: 6).flatMap { $0 }),
        Kid(name: "Shauna",
            family: Array(repeating: ["Ella", "Dan", "Humphrey"], count: 6).flatMap { $0 }),
        Kid(name: "Mildred",
            family: Array(repeating: ["Neil", "Glynis"], count: 6).flatMap { $0 }),
    ]

    //needs to be the same Type as whatever the scrollTo criteria will be
    @State private var firstFamilyMember: String = ""

    var body: some View {
        VStack {
            ScrollView {
                ForEach(kids) { kid in
                    Text(kid.name)
                        .onTapGesture {
                            //set the scrollTo criteria based on what gets tapped in the top list
                            firstFamilyMember = kid.family.first!
                        }
                }
            }
            Divider()
            ScrollView {
                ScrollViewReader { value in
                    ForEach(kids.flatMap(\.family), id: \.self) { fam in
                        Text(fam)
                    }
                    //the important thing here is that the onChange handler has to be
                    //INSIDE the ScrollViewReader since that's where we have access
                    //to the value of the reader and can change it

                    //watch for changes in the firstFamilyMember value...
                    .onChange(of: firstFamilyMember) { _ in
                        //...and jump to that value in the bottom list
                        value.scrollTo(firstFamilyMember, anchor: .top)
                    }
                }
            }
        }
    }
}

Note: I wasn't sure how your ExchangeRatesPB and ExchangeRatesNBU matched up, so that's why I didn't use your original code to demonstrate.

2      

Thanks @roosterboy for your help. I tried to implement this sollution to my project, but it still don't work.

ExchangeRatesPB and ExchangeRatesNBU have the same short name of some currencies: "USD", "EUR", "RUR"

2      

Okay, add an onChange modifier onto your bottom List like so:

List(currenciesNBU, id: \.self) { currencyNBU in
...
}
.onChange(of: choosenCurrency) { value in
    if let curr = currenciesNBU.first(where: { $0.cc == value }) {
        proxy.scrollTo(curr, anchor: .top)
    }
}

When the user taps on one of the ExchangeRatesPB items in the top List, you set choosenCurrency to the value of its ccy property. This modifier here triggers when choosenCurrency changes and finds the first ExchangeRatesNBU item that has a cc property that matches choosenCurrency and then scrolls the bottom list to that item.

(As an aside, I would highly recommend renaming the properties of your ExchangeRatesPB and ExchangeRatesNBU structs to make them more informative. Just because the JSON they are loaded from uses terrible names like ccy and r030 doesn't mean you have to. How we name things should relieve a lot of the cognitive work in figuring out what code is doing. You can use a CodingKeys enum to map the incoming names to the struct names.)

2      

WOOOW!😱😱😱 It's really working! Thanks @roosterboy for your help and advices!

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.