Load more functionality using SwiftUI - scrollview

i have used ScrollView with HStack, now i need to load more data when user reached scrolling at last.
var items: [Landmark]
i have used array of items which i am appeding in HStack using ForEach
ScrollView(showsHorizontalIndicator: false) {
HStack(alignment: .top, spacing: 0) {
ForEach(self.items) { landmark in
CategoryItem(landmark: landmark)
}
}
}
What is the best possible solution to manage load more in SwiftUI without using custom action like loadmore button.

It's better to use ForEach and List for this purpose
struct ContentView : View {
#State var textfieldText: String = "String "
private let chunkSize = 10
#State var range: Range<Int> = 0..<1
var body: some View {
List {
ForEach(range) { number in
Text("\(self.textfieldText) \(number)")
}
Button(action: loadMore) {
Text("Load more")
}
}
}
func loadMore() {
print("Load more...")
self.range = 0..<self.range.upperBound + self.chunkSize
}
}
In this example each time you press load more it increases range of State property. The same you can do for BindableObject.
If you want to do it automatically probably you should read about PullDownButton(I'm not sure if it works for PullUp)
UPD:
As an option you can download new items by using onAppear modifier on the last cell(it is a static button in this example)
var body: some View {
List {
ForEach(range) { number in
Text("\(self.textfieldText) \(number)")
}
Button(action: loadMore) {
Text("")
}
.onAppear {
DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime(uptimeNanoseconds: 10)) {
self.loadMore()
}
}
}
}
Keep in mind, that dispatch is necessary, because without it you will have an error saying "Updating table view while table view is updating). Possible you may using another async way to update the data

If you want to keep using List with Data instead of Range, you could implement the next script:
struct ContentView: View {
#State var items: [Landmark]
var body: some View {
List {
ForEach(self.items) { landmark in
CategoryItem(landmark: landmark)
.onAppear {
checkForMore(landmark)
}
}
}
}
func checkForMore(_ item: LandMark) {
guard let item = item else { return }
let thresholdIndex = items.index(items.endIndex, offsetBy: -5)
if items.firstIndex(where: { $0.id == item.id }) == thresholdIndex {
// function to request more data
getMoreLandMarks()
}
}
}
Probably you should work in a ViewModel and separate the logic from the UI.
Credits to Donny Wals: Complete example

Related

iOS16 - How to navigate through hidden links with an optional value?

I previously used an optional value to click a hidden link to navigate in my app. Something like this example in Hacking With Swift:
#State private var selection: String? = nil
var body: some View {
....
NavigationLink(destination: Text("View A"), tag: "A", selection: $selection) { EmptyView() }
NavigationLink(destination: Text("View B"), tag: "B", selection: $selection) { EmptyView() }
Button("Tap to show A") {
selection = "A"
}
Button("Tap to show B") {
selection = "B"
}
With iOS 16 this is deprecated. I am currently setting an optional value and when it's not nil I want a link to open. I can't figure out how to do it with the new NavigationLink/Value/Destination combination. Has anyone else figured out how to do it?
I created a new projects and switched ContentView to the following:
private enum Destinations: Hashable {
case empty
case general
case myQuestionView(String)
}
struct ContentView: View {
#State private var selection: Destinations?
#State private var mySelectedString: String?
var body: some View {
NavigationSplitView {
List(selection: $selection) {
NavigationLink(value: Destinations.general) {
Text("Example")
}
if mySelectedString != nil {
NavigationLink(value: Destinations.myQuestionView(mySelectedString!)) {
Text("String: \(mySelectedString ?? "no name")")
}
}
Button(action: {
mySelectedString = "A Name"
}, label: {
Text("Set the value")
})
}
} detail: {
NavigationStack {
switch selection ?? .empty {
case .empty: Text("Please select an option to continue.")
case .general: Text("Result of this option")
case .myQuestionView(let aString): Text("Hello \(aString)")
}
}
}
}
}
Here the Set the value button sets the selectedString which makes the link appear but I can't make it automatically navigate AND, ideally, it would never appear and would navigate when the value is set.
Okay... the answer is super simple and leaving the question and this answer up in case it helps someone else.
You don't need to have an invisible NavigationLink. You just need to set the selection to the new destination: selection = .myQuestionView("this name instead"). Or, if I was using the navigation path NavigationStack(path: $myPath) I'd just append it.
So in this specific example ContentView would now be:
private enum Destinations: Hashable {
case empty
case general
case myQuestionView(String)
}
struct ContentView: View {
#State private var selection: Destinations?
var body: some View {
NavigationSplitView {
List(selection: $selection) {
NavigationLink(value: Destinations.general) {
Text("Example")
}
Button(action: {
selection = .myQuestionView("this name instead")
}, label: {
Text("Set the value")
})
}
} detail: {
NavigationStack {
switch selection ?? .empty {
case .empty: Text("Please select an option to continue.")
case .general: Text("Result of this option")
case .myQuestionView(let aString): Text("Hello \(aString)")
}
}
}
}
}

Better way to raise number pad SwiftUI

Upon navigating to a view, I want the number pad to already be raised. Right now I have a solution that works the first time (albeit with a delay) but fails to raise the number pad if the user navigates back a second time. Is there a better way to raise the number pad in SwiftUI (or to have it always up)?
Example Code:
struct ParentView: View {
#FocusState var numberPadFocused: Bool
#State var isActive: Bool = false
var body: some View {
NavigationView {
VStack {
Button {
numberPadFocused = true
isActive = true
print("Called")
} label: {
Text("Navigate")
}
NavigationLink(destination: ChildView(focusState: $numberPadFocused), isActive: $isActive) { Color.white }
}
}
}
}
struct ChildView: View {
#State var text: String = ""
#FocusState.Binding var focusState: Bool
var body: some View {
TextField("Enter Number...", text: $text)
.keyboardType(.numberPad)
.focused($focusState)
}
}

How do I change the variable value in a different file in Swiftui

I set a variable in the contentview #State var shouldShowModal = false, i want to change it once i press a button shouldShowModal = false. I keep getting Cannot find 'shouldShowModal' in scope.
Here is a working example, passing the value through #Bindings. Read more about #Binding here, or the official documentation.
This means that you can now do shouldShowModal = false with the binding, which will also update the body of the original view containing #State.
struct ContentView: View {
#State private var shouldShowModal = false
var body: some View {
VStack {
Text("Hello world!")
.sheet(isPresented: $shouldShowModal) {
Text("Modal")
}
OtherView(shouldShowModal: $shouldShowModal)
}
}
}
struct OtherView: View {
#Binding var shouldShowModal: Bool
var body: some View {
VStack {
Text("Should show modal: \(shouldShowModal ? "yes" : "no")")
Toggle("Toggle modal", isOn: $shouldShowModal)
}
}
}

Can I disable Navigationlink for a specified set of cells in my SwiftUI list?

I am working on a contacts app in SwiftUI for work which will display hundreds of phone numbers. Some contacts have a detail view with address and alternate numbers, while some contacts do not.
For example, Harry Smith will have basic phone extension listed in row while his cell number and address are listed in detail view.
But the number for the Second Floor Bathroom only needs the basic phone extension in the row, a detail view containing cell number and address for the bathroom is unnecessary.
How do I disable navigation link for those contacts who do not have pertinent detail info?
I prefer to add NavigationLink on condition.
I will have a "Cell" with some contents. (image/file detail)
A - build a "content" View:
struct MediumFileContentRow: View {
var file: MediumFile
var body: some View {
VStack (alignment: .leading) {
let (name, attribs) = file.getInfo() // get from model..
Text(name)
Spacer()
Text(attribs)
}// VStack
}
}
B - Your cell (MediumFileRow) will conditionally add link (NavigationLink) "around" our content view, and will give back different Views using AnyView:
struct MediumFileRow: View {
var file: MediumFile
var body: some View {
let enabled = NavigationLink(destination: Detail(t: file.name!)) {
MediumFileContentRow(file: file)
}
let disabled = MediumFileContentRow(file: file)
return file.isEmpty ? AnyView(disabled) : AnyView(enabled)
}
All (almoast..) The code:
struct MediumFileContentRow: View {
var file: MediumFile
var body: some View {
VStack (alignment: .leading) {
let (s,sd) = file.displayed()
Text(s)
Spacer()
Text(sd).font(.system(size: 9.0))
}// VStack
}
}
struct MediumFileRow: View {
var file: MediumFile
var body: some View {
let enabled = NavigationLink(destination: Detail(t: file.name!)) {
MediumFileContentRow(file: file)
}
let disabled = MediumFileContentRow(file: file)
return file.isEmpty ? AnyView(disabled) : AnyView(enabled)
}
...
..
In list You will have:
var body: some View {
NavigationView{
....
List {
ForEach(mediumFiles, id: \.self) { file in
MediumFileRow(file: file)
}
}
......
advantage: You can easily customise "disabled" cells.

SwiftUI with ObservableObject - List having NavigationLink to details downloading it on scroll NOT on appear

I have list of cities
struct CityListView: View {
#ObservedObject private(set) var citiesViewModel: CitiesViewModel
var body: some View {
LoadingView(isShowing: .constant(citiesViewModel.cities?.isEmpty ?? false)) {
NavigationView {
List(self.citiesViewModel.cities ?? []) { city in
NavigationLink(destination: DetailView(cityName: city.name,
detailCityModel: DetailCityModel(cityId: city.id))) {
Text(city.name)
}
}
.navigationBarTitle(Text("Cities"), displayMode: .large)
}
}
}
}
and when I'm scrolling the list, the DetailCityModel inits and download data from API. How to downloading (or init DetailCityModel) on DetailView's appearance, not for showing item with NAvigationLink to DetailView?
You have to kick off the API call in onAppear() not in the initialiser of DetailView.