繁体   English   中英

如何在 SwiftUI 中的秒数后显示文本视图?

[英]How to show a Text view after amount of seconds in SwiftUI?

当用户将设备保持启动时间过长(大约 3-4 秒)时,我想显示一条文本说“保持设备垂直以继续”。 我能做些什么? 任何建议表示赞赏...

这是代码的样子:

import SwiftUI
import CoreMotion

struct ContentView: View {

    let motionManager = CMMotionManager()
    let queue = OperationQueue()
    @State private var roll = Double.zero
    
    let timer = Timer.publish(every: 1, tolerance: 0.5, on: .main, in: .common).autoconnect()
    @State private var timeRemaining = 30

    var body: some View {
        VStack {
            Text("You have \(timeRemaining) seconds left")
                .onReceive(timer) { _ in
                    if timeRemaining > 0 {
                        timeRemaining -= 1
                    }
                }
            if roll < 1 {
            //Show "HIGH" if the user raises head
                Text("HIGH")
            } else if roll > 2.1 {
            //Show "LOW" if user lowers head
                Text("LOW")
            } else {
            //Otherwise show another Text view
                Text("Move the device!")
            }
        }
        .onAppear {
            //Detect device motion
            self.motionManager.startDeviceMotionUpdates(to: self.queue) { (data: CMDeviceMotion?, error: Error?) in
                guard let data = data else {
                    print("Error: \(error!)")
                    return
                }
                let attitude: CMAttitude = data.attitude
                
                DispatchQueue.main.async {
                    self.roll = attitude.roll
                }
            }
        }
    }
}

选项 1(较少更改)

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    //Do your work, will run after 3 seconds               
}

选项2(我的偏好)

概念

  • 使用Task.sleep(nanoseconds:) - 这是一个异步 function 将暂停 n 纳秒。 它不会阻塞主线程
  • task { }中使用它,当视图出现时调用它并用于执行任何异步工作
  • 很高兴了解 Swift 并发以及它如何与 SwiftUI 一起使用

示例代码

struct ContentView: View {
    @State private var roll = Double.zero
    
    var body: some View {
        VStack {
            Text("Hello World!")
            
            if roll < 1 {
                //Show "HIGH" if the user raises head
                Text("HIGH")
            } else if roll > 2.1 {
                //Show "LOW" if user lowers head
                Text("LOW")
            } else {
                //Otherwise show another Text view
                Text("Move the device!")
            }
        }
        .task {
            //Suspends for 3 seconds
            try? await Task.sleep(nanoseconds: 3_000_000_000)
            roll = 3
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM