如何检测某个视图正在 SwiftUI 的屏幕上显示

How to detect that a certain view is being displayed on screen in SwiftUI

我正在为如何检测某个视图正在屏幕上显示而苦恼。

我有一个通知列表,其中新的通知单元格具有蓝色背景,在您看到通知 2 秒后,背景变为白色,这意味着您已经看到了新通知,就像在 Twitter 的新通知屏幕中一样.

首先我考虑使用 onAppear 修饰符来检测您是否看到了新的通知单元格,但它在特定单元格显示在屏幕上之前就被触发了。

所以我想出了一个解决方法。当通知底部选项卡被选中时,即当用户从另一个视图来到通知视图时,然后 2 秒后更改新通知单元格的背景。


struct NotificationCell: View {

@Binding var tabSelection: TabBarItem
@Binding var notificationsDetail: NotificationsDetail

var body: some View {

HStack {
 //Views inside
}
.background(notificationsDetail.notificationsIsAlreadyRead ? .white : .blue)

 }
}

但是,我不知道在哪里写下面的代码,因为init() 或onAppear 一开始只触发一次。当 tabSelection 属性 更改时,我需要确保我 运行 代码。

  if tabSelection == .notifications {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                    notificationsDetail.notificationsIsAlreadyRead = true
                }
            }

我也研究了 onChange 修饰符,但由于我没有使用 Texts 或 TexFields,我认为 onChange 可能不适合作为解决方案。

也许我的解决方法首先不是实现我想做的事情的好方法。

如有任何建议,我们将不胜感激。

提前致谢。

onChange 在这里起作用。

.onChange(of: tabSelection) { selection in
    if selection == .notifications {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            notificationsDetail.notificationsIsAlreadyRead = true
        }
    }
}