在 Swift/SwiftUI 中仅显示来自 Date 对象的时间 [英] Displaying only time from a Date object in Swift/SwiftUI

查看:70
本文介绍了在 Swift/SwiftUI 中仅显示来自 Date 对象的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用结束时间显示音频持续时间.一位优秀的 Stack Overflow 开发人员提出了这个解决方案.

I've been working with displaying audio duration with ending time. One of the good Stack Overflow developers suggested this solution.

因此,我已将其添加到我的视图中:

Hence, I've added this in my view:

struct ContentView: View {
    @ObservedObject var viewModel = MyViewModel() //<- here
    var body: some View {
        VStack {
            
            Text(viewModel.endTime) //<- here
            
        }
    }
}

这是我的viewModel中的代码:

class MyViewModel: ObservableObject {
    @Published var endDate: Date? 
    var endTime: String{
        endDate == nil ? "":endDate!.description 
    }

    func play(){
        let path = Bundle.main.path(forResource: "song", ofType:"mp3")!
        let url = URL(fileURLWithPath: path)
        do {
            player = try AVAudioPlayer(contentsOf: url)
            
            endDate = Date() + player.duration
            if player.isPlaying{
                
                player.pause()
                
            }
            else{
                player.play()
                
            }
            isPlaying = player.isPlaying
        }catch{print("error")}

但是我得到了错误的时间(不是系统时间)但是日期正确.我只想显示正确的时间而不显示日期.

But I'm getting the wrong time (not the system time) but with the correct date. I want to display only the correct time without date.

推荐答案

要显示格式化的日期,您可能需要使用 DateFormatter:

To display a formatted date, you'll probably want to use DateFormatter:

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
 
let date = Date(timeIntervalSinceReferenceDate: 118800)
 
// US English Locale (en_US)
dateFormatter.locale = Locale(identifier: "en_US")
print(dateFormatter.string(from: date)) // Jan 2, 2001

来源:https://developer.apple.com/documentation/foundation/dateformatter

(请注意,众所周知,创建 DateFormatter 是一项开销很大的操作,因此请注意不要过于频繁地创建它们)

(Note that creating a DateFormatter is known to be an expensive operation so be careful about creating them too often)

您的视图模型中也有一些逻辑错误.以下是如何处理此问题的示例:

You have a couple of logic errors in your view model as well. Here's an example of how to handle this:

struct ContentView : View {
    @ObservedObject private var vm = MyViewModel()
    
    var body: some View {
        Button(action:{
            vm.play()
        } ) {
            Text(vm.isPlaying ? "Stop" : "Play")
        }
        Text(vm.endTime)
    }
}

class MyViewModel: ObservableObject {
    @Published var endDate: Date?
    @Published var isPlaying = false
    
    var player = AVAudioPlayer()
    var dateFormatter = DateFormatter()
    
    var endTime: String{
        guard let endDate = endDate else {
            return ""
        }
        dateFormatter.dateStyle = .none
        dateFormatter.timeStyle = .medium
        return dateFormatter.string(from: endDate)
    }

    func play(){
        do{
            if player.isPlaying {
                player.pause()
            } else {
                let path = Bundle.main.path(forResource: "All Of Me Final Mix", ofType:"mp3")!
                let url = URL(fileURLWithPath: path)
                player = try AVAudioPlayer(contentsOf: url)
                endDate = Date() + player.duration - player.currentTime
                player.play()
            }
            isPlaying = player.isPlaying
        } catch {
            print("error: \(error)")
        }
    }
}

这篇关于在 Swift/SwiftUI 中仅显示来自 Date 对象的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆