使用LazyVGrid或LazyVStack时按钮中的图标切换不一致

如何解决使用LazyVGrid或LazyVStack时按钮中的图标切换不一致

我目前正在尝试通过实施一个小项目来学习SwiftUI。为此,我在LazyVGrid(游戏列表视图)中列出了视频游戏及其封面和标题(游戏卡视图)。从URL进行显示和异步加载图像已经很好用了。

现在,我尝试集成收藏夹功能。为此,我在每个GameCard视图中显示一个按钮,根据用户默认值中是否提供了游戏ID,该按钮显示空心或空心。该按钮的操作随时可用:如果“游戏ID”已经在“用户默认设置”中,则该ID将被删除。如果尚不存在,它将被添加。这可以通过prints()轻松观察到。切换心脏图标的效果并不理想:如果我将LazyVGrid进一步向下滚动到最初不可见的区域,然后按下按钮,有时(并非总是如此!)会发生图标没有被替换的情况(即使该操作已触发)。

我的猜测是这是由于LazyVGrid或LazyVStack引起的。如果我在普通的VStack中显示游戏卡,则无法重现该现象。

您是否知道如何解决此问题?是什么原因?

有关更多上下文,请参见下面的一些实现摘要。我正在谈论的按钮位于GameCard.swift中,其中包含Image(systemName: favorites.contains(self.game) ? "heart.fill" : "heart")

GameListView.swift

struct GameListView: View {

@Binding var loadGames: Bool

@ObservedObject var gameList: GameList = GameList()

@ObservedObject var favorites = Favorites()

@State private var selectedGame: Game? = nil

@State private var searchText = ""

init(loadGames: Binding<Bool>) {
    self._loadGames = loadGames     
    ...
}

let layout = [
    GridItem(.flexible(),spacing: 16),GridItem(.flexible(),spacing: 16)
]


var body: some View {
        NavigationView {
            ZStack {
                Color.black
                    .edgesIgnoringSafeArea(.all)
            ScrollView {
                SearchBarView(searchText: $searchText)
                    .padding(.top,16.0)
                if gameList.isLoading {
                    Text("Loading")
                        .foregroundColor(Color.white)
                } else {
                LazyVGrid(columns: layout,spacing: 16) {
                    ForEach(gameList.games.filter{$0.name.contains(searchText) || searchText == ""}) {game in
                        GameCard(game: game)
                            .onTapGesture {
                                self.selectedGame = game
                                print(self.selectedGame!)
                            }
                    }
                }
                .sheet(item: $selectedGame) { game in
                    GameDetail(game: game)
                    }
                .padding(.all)
                .background(Color.black)
                .edgesIgnoringSafeArea(.all)
                .navigationBarTitle("Upcoming Games")
                .resignKeyboardOnDragGesture()
                }
            }
            }
        }.onAppear {
            if loadGames {
                self.gameList.reload()
                loadGames = false
            }
        }
        .environmentObject(favorites)
    }
}

GameCard.swift

struct GameCard: View {

var game: Game

@Environment(\.imageCache) var cache: ImageCache

@EnvironmentObject var favorites: Favorites

var body: some View {
        VStack(alignment: .leading) {
            ZStack(alignment: .topTrailing) {
                AsyncImage(
                   url: game.coverURL!,cache: self.cache,placeholder: Text(game.name),configuration: { $0.resizable() }
                )
                .cornerRadius(4.0)
                .aspectRatio(contentMode: .fit)
                Button(action: {
                    if self.favorites.contains(self.game) {
                        print("Remove Game from Favs")
                        self.favorites.remove(self.game)
                    } else {
                        print("Add Game to Favs")
                        self.favorites.add(self.game)
                    }
                }) {
                    Image(systemName: favorites.contains(self.game) ? "heart.fill" : "heart")
                        .imageScale(.large)
                }
                .padding([.top,.trailing])
            }
            Text(game.name)
                .font(.body)
                .foregroundColor(Color.white)
                .fontWeight(.semibold)
                .lineLimit(1)
                .lineSpacing(32)
                .padding(.bottom,0.5)
            Text(game.releaseDateText)
                .font(.subheadline)
                .foregroundColor(Color.gray)
                .lineLimit(0)
        }
        .padding(.all,8.0)
        .background(Color(red: 1.0,green: 1.0,blue: 1.0,opacity: 0.15))
        .cornerRadius(8.0)
    }
}

更新:我添加了收藏夹.swift的实现。这是触发视图更改的地方。

class Favorites: ObservableObject {

//The fetched games by id are stored here.
@Published var favGames: [Game] = []

@Published var isLoading = false

var gameService = Store.shared

let userDefaults = UserDefaults.standard

// the key we're using to read/write in UserDefaults
private let saveKey = "Favorites"

// the actual game ids the user has favorited
var games: [String]

init() {
    // load our saved data
    self.games = userDefaults.stringArray(forKey: saveKey) ?? []
}

// returns true if set contains the game
func contains(_ game: Game) -> Bool {
    return games.contains(String(game.id))
}

// adds gams to set,updates all views,and saves the change
func add(_ game: Game) {
    objectWillChange.send()
    games.append(String(game.id))
    save()
}

// removes the game from  set,and saves the change
func remove(_ game: Game) {
    objectWillChange.send()
    games.remove(object: String(game.id))
    save()
}

func save() {
    // write out our data
    UserDefaults.standard.set(self.games,forKey: saveKey)
    print(games)
    print("Saved new set of favorites")
}
    
func reload() {
    self.favGames = []
    self.isLoading = true
            
    gameService.fetchGamesById(id: self.games) { [weak self]  (result) in
        self?.isLoading = false

        switch result {
        case .success(let games):
            self?.favGames = games

        case .failure(let error):
            print(error.localizedDescription)
        }
      }
   }
}

extension Array where Element: Equatable {

// Remove first collection element that is equal to the given `object`:
mutating func remove(object: Element) {
    guard let index = firstIndex(of: object) else {return}
    remove(at: index)
    }

}

解决方法

通过实际发布和查看“ Favorites.swift”实现(感谢@Asperi),我认为我发现了这个问题(至少不再可复制):

objectWillSend.send()games.append(String(game.id))games.remove(String(game.id))函数的addremove之前被调用,这些函数由GameCard.swift中的按钮动作调用。我认为这导致在某些情况下甚至在将游戏添加到收藏夹或从收藏夹中删除之前更新视图。

我现在想知道,为什么在常规VStack中不是这种情况。 也许有人可以对此进行详细说明?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-