简体   繁体   English

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

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

I would like to show a Text saying "Keep the device vertical to continue" when the user keeps the device up for too long (around 3-4 seconds).当用户将设备保持启动时间过长(大约 3-4 秒)时,我想显示一条文本说“保持设备垂直以继续”。 What can I do?我能做些什么? Any suggestions appreciated...任何建议表示赞赏...

This is how the code looks like:这是代码的样子:

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
                }
            }
        }
    }
}

Option 1 (less changes)选项 1(较少更改)

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

Option 2 (my preference)选项2(我的偏好)

Concept概念

  • Use Task.sleep(nanoseconds:) - This is an async function which will suspend for n nanoseconds.使用Task.sleep(nanoseconds:) - 这是一个异步 function 将暂停 n 纳秒。 It will not block the main thread它不会阻塞主线程
  • Use it inside task { } which gets called when view appears and is used to do any async worktask { }中使用它,当视图出现时调用它并用于执行任何异步工作
  • Would be nice to learn about Swift Concurrency and how it can be used with SwiftUI很高兴了解 Swift 并发以及它如何与 SwiftUI 一起使用

Sample Code示例代码

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