在SwiftUI中单击菜单切换URL时如何实现

时间:2020-02-12 05:43:09

标签: ios json swiftui

我正在使用SwiftUI开发新闻应用程序。当用户单击菜单并切换url并重新加载列表视图时,我正在搜索。请看下面的图片。

enter image description here

这是我要实现的代码。 MenuItem.swift

import Foundation
import SwiftUI

struct MenuItem: View {

    @ObservedObject var networkManager = NetworkManager()
    @State private var menuPressed = false
    var itemData: ItemData
    var body: some View {

        VStack(alignment: .center){
            Text(self.itemData.title)
                .fontWeight(.semibold)
                .font(.subheadline)
                .onTapGesture {

                    print("Tap at \(self.itemData.title), url: \(self.itemData.url)")
                    self.menuClik()

            }
        }.frame(height: 15)
            .padding(.all)
            .foregroundColor(Color.gray)
            .background(Color.black)
            .cornerRadius(30)
        }

    func menuClik(){
        self.networkManager.urlString = self.itemData.url
        //print(self.networkManager.urlString)
        self.networkManager.clear()
        self.networkManager.fetchData()
    }
}

这是我的NetworkManager.swift

class NetworkManager: ObservableObject{
let url = "http://example.com/wp-json/wp/v2/posts?_embed=1&page=1"
let urlCage = "http://example.com/wp-json/wp/v2/posts?_embed=1&page=1&categories=17"
var urlString = ""
@Published var dataList = [TaiFreedomData]()
@Published var isLoading = false

init(){
    isLoading = true
    fetchData()
}

func clear(){
    self.dataList = []
}

func fetchData() {
    print(urlString)
    if urlString == "" {
    guard let url = URL(string: urlCage) else {return}
        URLSession.shared.dataTask(with: url) {
            (data, _, _) in
            guard let data = data else {return print(Error.self)}

            let dataList = try! JSONDecoder().decode([TaiFreedomData].self, from: data)

            DispatchQueue.main.async {
                self.dataList = dataList
               // print(dataList.self)
            }
        }.resume()
    }else{
    guard let url = URL(string: urlString) else {return}
        URLSession.shared.dataTask(with: url) {
            (data, _, _) in
            guard let data = data else {return print(Error.self)}

            let dataList = try! JSONDecoder().decode([TaiFreedomData].self, from: data)

            DispatchQueue.main.async {
                self.dataList = dataList
               // print(dataList.self)
            }
        }.resume()
    }//end if else


    }

    }

这是我的主要ContentView.swift

    struct ContentView: View {

    @ObservedObject var networkManager = NetworkManager()
    var itemData : [ItemData]
    var body: some View {

        NavigationView{
            ZStack(){
                if (networkManager.isLoading){
                HStack(alignment: .top, spacing: 10){
                    VStack(){
                        //item
                        HStack{
                            ScrollView(.horizontal, showsIndicators: false){
                                HStack(spacing: 10){
                                    ForEach(self.itemData, id: \.title) {
                                        item in
                                        MenuItem(itemData: item)
                                    }
                                }

                            }
                        }
                        //News title
                        Divider()
                        HStack{
                            ScrollView(.horizontal, showsIndicators: false){
                                HStack{
                                    ForEach(networkManager.dataList, id: \.id) { data in
                                        NewsBannerCard(data: data)
                                    }
                                }
                            }

                            Spacer()
                        }

                        //Releated News
                        Text("Latest News").font(.headline).bold()
                        Divider()
                        HStack{
                        List(networkManager.dataList.self, id: \.id) { data in                            
                            NavigationLink(destination: TFDDetails(data: data)){
                                ReleatedNewsImage(data: data)
                            }
                            .navigationBarTitle(Text("Tai Freedom").bold())
                            .navigationBarItems(trailing: Button("Clear"){
                                self.networkManager.clear()
                                })
                        }
                        }
                    }

                }
                }else{
                    Text("Loading ...")
                }
            }.onAppear(){
            self.networkManager.fetchData()
        }
        //end NaviationView
        }

    }
}

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

当用户单击菜单,从NetworkManager切换url并重新加载新闻内容并显示在列表视图中时,我想实现。我应该怎么做?请帮我!先生。

0 个答案:

没有答案