SwiftUI 添加到收藏夹

Posted

技术标签:

【中文标题】SwiftUI 添加到收藏夹【英文标题】:SwiftUI Add to favorites 【发布时间】:2020-08-07 00:01:05 【问题描述】:

我正在尝试创建一个收藏列表,允许用户在搜索时将节目添加到他们的库中,但我尝试过的所有方法都没有奏效。谁能帮我创建一个可以做到这一点的函数?

代码如下:

import SwiftUI
import Combine

class APIStore: ObservableObject 
    
    @Published var serieses: [Series] = []
    @Published var seasons: [Season] = []
    @Published var episodes: [Episode] = []
    @Published var casts: [CastCrew] = []
    @Published var crews: [CastCrew] = []

    init() 
        serieses = []
        seasons = []
        episodes = []
        casts = []
        crews = []
    
    
    func fetchSeries(pageNumber: Int = 1)  
        
        let params = [
            ("page", String(pageNumber))
        ]
        ApiMapper().callAPI(withPath: AppData.show, params: params, andMappingModel: [Series].self)  [weak self] (result) in
            switch(result) 
            case .success(let serieses):
                DispatchQueue.main.async 
                    self?.serieses = serieses
                
            case .failure(_):
                break
            
        
    
    
    func searchSeries(searchString: String)  
           
           let params = [
               ("q", searchString)
           ]
           ApiMapper().callAPI(withPath: AppData.search, params: params, andMappingModel: [SearchResult].self)  [weak self] (result) in
               switch(result) 
               case .success(let searchResult):
                   DispatchQueue.main.async 
                    self?.serieses = searchResult.compactMap($0.series)
                   
               case .failure(_):
                   break
               
           
       
  

这里是我想要添加收藏按钮的地方,但我无法做到


import SwiftUI
import SDWebImageSwiftUI

struct HomeView: View 
    
    @ObservedObject var apiStore  = APIStore()
    @ObservedObject var userShows = UserShowList()
    @State private var searchString = ""
    @State private var pageNumber = 1
    @State var selectedSeason: Int
    
    
    init(selectedSeason: Int) 
        UITableView.appearance().separatorStyle = .none
        _selectedSeason = State(initialValue: selectedSeason)
        //        self.series = series
    
    
    var body: some View 
        NavigationView() 
            VStack(alignment: .leading, spacing: 5.0) 
                TextField("Search", text: $searchString, onEditingChanged:  status in
                    if !status && self.searchString != "" 
                        self.apiStore.searchSeries(searchString: self.searchString)
                        self.pageNumber = 1
                    
                    //                    else if !status && self.searchString == "" 
                    //                        self.apiStore.fetchSeries(pageNumber: self.pageNumber)
                    //                    
                )
                    .padding(.all, 10.0)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                List
                    ForEach(self.apiStore.serieses)  series in
                        HStack 
                            SeriesCell(series : series, selectedSeason: self.$selectedSeason)
                                .onAppear 
                                    if series.id == self.apiStore.serieses.last?.id 
                                        self.pageNumber += 1
                                        self.apiStore.fetchSeries(pageNumber: self.pageNumber)
                                    
                            
                        
                    
                
                .padding(.leading, -10.0)
                .frame(width: screen.width)
                .navigationBarTitle("Shows", displayMode: .inline)
                .onAppear 
                    self.apiStore.searchSeries(searchString: self.searchString)
                
            
            .environmentObject(userShows)
        
    



struct SeriesCell: View 
    
    var series: Series
    @Binding var selectedSeason: Int
    
    var seriesDate: String 
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy-MM-dd"
        if let date = formatter.date(from: series.premiered ?? "") 
            formatter.dateFormat = "yyyy"
            return formatter.string(from: date)
         else 
            return series.premiered ?? ""
        
    
    
    var body: some View 
        NavigationLink(destination: DetailsView(series: series, selectedSeason: selectedSeason)) 
            VStack(alignment: .leading) 
                HStack(alignment: .center) 
                    ZStack 
                        WebImage(url: URL(string: (series.image?.original ?? "")))
                            .placeholderImage(systemName: "tv.circle.fill").foregroundColor(Color.white)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 50, height: 73, alignment: .center)
                            .clipShape(RoundedRectangle(cornerRadius: 10, style: .circular))
                    
                    
                    VStack(alignment: .leading, spacing: 5.0) 
                        Text(String(series.name ?? ""))
                            .font(.body)
                            .multilineTextAlignment(.leading)
                            .font(.title)
                        
                        Text(seriesDate)
                            .font(.subheadline)
                    
                
            
            .frame(width: screen.width, alignment: .leading)
        
    

【问题讨论】:

【参考方案1】:

您可以尝试将“isFavourite: Bool”实例添加到您的 Season 类中。然后在创建收藏夹视图时,您可以遍历所有季节并仅显示该实例为 true 的那些

【讨论】:

以上是关于SwiftUI 添加到收藏夹的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI CoreData - 如何更新获取请求和列表

使用 SwiftUI 从转换目的地返回时,我想将显示的列表更新为最新状态

SwiftUI - 使用按钮切换“收藏”动态项目

SwiftUI 列表未使用 ForEach 正确更新

怎样把我在收藏夹里的其他网页,也添加到百度收藏里?

添加到收藏夹功能 [swift]