【问题标题】:SwiftUI - Button not switching imageSwiftUI - 按钮不切换图像
【发布时间】:2021-09-11 16:28:05
【问题描述】:

所以在尝试让播放器播放和暂停按钮时发生了一个非常愚蠢的问题。所以我在顶部创建了一个@State

    @State var isPlaying  : Bool = false

然后是按钮

        Button(action: {
                                    self.isPlaying.toggle()
                                    if self.isPlaying {
                                       player.pause()
                                  }
                                  else {
                                    player.play()
                                  }
                                    
                                }) {
                                    Image(systemName: self.isPlaying ? "pause" : "play.fill")
                                }
                                .foregroundColor(.white)
                                .font(.system(size:34))
                               

它可以工作,但在点击时它会播放视频,而不会在视频运行时将 sfSymbol 从播放切换为暂停。它只是在播放和暂停时使用 player.fill 来处理两种状态。

【问题讨论】:

  • 无法重现此问题。提供的代码工作正常。 Xcode 版本:12.5.1 (12E507)。模拟器版本:12.5.1 (961.1)。注意:由于您没有提供足够的代码,我将“player.pause() / .start() 更改为 print()”

标签: swift button swiftui boolean


【解决方案1】:

编辑更新:

也适合我。这是我用于测试的代码:

import Foundation
import SwiftUI
import CoreMedia
import AVFoundation
import AVKit

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
struct ContentView: View {
    @State var isPlaying = false
    let player = AVPlayer(url: URL(string: "https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4")!)
    
    var body: some View {
        VStack {
            Button(action: {
                isPlaying.toggle()
                if isPlaying {
                    player.pause()
                } else {
                    player.play()
                }
            }) {
                Image(systemName: isPlaying ? "pause" : "play.fill")
            }
            VideoPlayer(player: player)
        }.font(.system(size:34))
    }
}

【讨论】:

    猜你喜欢
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2014-07-11
    相关资源
    最近更新 更多