Created
April 7, 2020 00:35
-
-
Save mfdeveloper/2c88ae6e861e00e51a38bff873219db8 to your computer and use it in GitHub Desktop.
SwiftUI code snippet example with a Custom View inside in another custom view (InnerContentView => ContentView)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // ContentView.swift | |
| // FlickrImages | |
| // | |
| // Created by Felipe on 27/03/2020. | |
| // Copyright © 2020 darkness. All rights reserved. | |
| // | |
| import SwiftUI | |
| struct InnerContentView: View { | |
| var parent: ContentView? = nil | |
| @ObservedObject | |
| var imgsVm = ImagesViewModel() | |
| @State | |
| var searchTerm: String = "" | |
| var body: some View { | |
| VStack { | |
| NavigationView { | |
| ScrollView { | |
| SearchBar(text: self.$searchTerm) | |
| ImagesRow(collection: self.imgsVm.imgs) | |
| }.navigationBarTitle(Text("Flickr Images")) | |
| .navigationBarItems(trailing: Button(action: { | |
| ContentView.loadData(content: self) | |
| }, label: { | |
| Text("Search") | |
| })) | |
| } | |
| }.onAppear { | |
| ContentView.loadData(content: self) | |
| } | |
| } | |
| } | |
| struct ContentView: View { | |
| @State | |
| var showLoadingView: Bool = false | |
| var body: some View { | |
| ActivityIndicatorView(isShowing: .constant(showLoadingView)) { | |
| InnerContentView(parent: self) | |
| } | |
| } | |
| /** | |
| # Load photos data | |
| Request a REST API and return the array data to a @Published variable | |
| # Attention | |
| > **PS:** This method is static to avoid error: `scaping closure captures mutating 'self'` | |
| Because this problem, that method exists, and the method `ImagesViewModel.fetchSearch` is not | |
| executed in `self.init()`, for example | |
| */ | |
| static func loadData(content: InnerContentView, after afterLoad: (() -> Void)? = nil) { | |
| if content.parent != nil { | |
| content.parent!.showLoadingView = true; | |
| } | |
| content.imgsVm.fetchSearch(tags: content.searchTerm) { | |
| if content.parent != nil { | |
| content.parent!.showLoadingView = false; | |
| } | |
| if afterLoad != nil { | |
| afterLoad!() | |
| } | |
| } | |
| } | |
| } | |
| #if DEBUG | |
| struct ContentView_Previews: PreviewProvider { | |
| static var previews: some View { | |
| ContentView().onAppear() | |
| } | |
| } | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment