跳转到内容
View in the app

A better way to browse. Learn more.

彼岸论坛

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.
欢迎抵达彼岸 彼岸花开 此处谁在 -彼岸论坛

[iDev] Swift UI 用 Timer 每秒更新 Text 时文字会出现残影

发表于

想在 app 里加一个页面显示当前的系统时间,精确到秒,网上查到的资料都是推荐用 Timer 每秒触发一次更新。

struct AtomicClockView: View {
    @State private var currentDate = Date.now
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    var body: some View {
        Text(currentDate.formatted(date: .omitted, time: .standard))
            .font(.system(size: 50, weight: .ultraLight, design: .monospaced))
            .onReceive(timer) { input in
                currentDate = input
            }
    }
}

然后放在 TabView 里了

var body: some View {
        NavigationStack {
            TabView {
                AtomicClockView()
                    .tabItem {
                        Label("Atomic Clock", systemImage: "clock")
                    }
            }
        }
    }

在 Xcode 里预览和模拟器里看起来都一切正常,但是在手机( iPhone 14 Pro, iOS 18 )上打开之后,可以明显感到秒的文字在更新时会有上一秒的残影叠加在上面,而不是瞬间消失再渲染下一秒。

搜索了一下好像没有人提过类似的问题,所以不知道是 SwiftUI 的问题还是代码的问题,每秒一次的频率应该不会是性能问题吧(尝试把 Timer 改成 0.1 也无法解决)。

感谢帮助。

Featured Replies

No posts to show

创建帐户或登录来提出意见

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.