如何修复SwiftUI的.onChange(of:perform)以消除Xcode弃用警告?
解决SwiftUI
onChange 弃用警告问题 问题原因
macOS 14.0之后,SwiftUI弃用了仅接收新值的onChange(of:perform:)重载方法,官方要求改用带两个参数(旧值+新值)或者零参数的闭包形式。
解决方案
根据你的代码需求,有三种可行的修改方式:
1. 忽略旧值,仅保留新值
如果不需要用到旧值,用下划线_占位忽略即可,逻辑和原来完全一致:
.onChange(of: thisImageIndex) { _, newValue in // Update currentDatum when the index changes if newValue >= 0 && newValue < imageList.count { currentDatum = imageList[newValue] imageCaption = currentDatum!.displayName } }
2. 同时接收旧值和新值
如果以后需要对比新旧值做额外逻辑,可以保留两个参数:
.onChange(of: thisImageIndex) { oldValue, newValue in // 可在这里添加新旧值对比逻辑(示例) if oldValue != newValue { if newValue >= 0 && newValue < imageList.count { currentDatum = imageList[newValue] imageCaption = currentDatum!.displayName } } }
3. 零参数闭包(直接读取当前值)
也可以用零参数的闭包,直接访问thisImageIndex的当前值:
.onChange(of: thisImageIndex) { let newValue = thisImageIndex if newValue >= 0 && newValue < imageList.count { currentDatum = imageList[newValue] imageCaption = currentDatum!.displayName } }
以上三种写法都能消除弃用警告,且完全适配macOS 15系统。
内容的提问来源于stack exchange,提问作者Nate Lockwood
相关产品推荐
相关产品推荐

