我将selectedIndexInt的值从ContentView结构体获取到结构体中的LoopingPlayerUIView类时遇到问题,selectedIndex用于tabvview,我想在类中获取它的值以播放或暂停视频
下面是一个脚本的剪切:
struct ContentView: View {
//...
@State public var selectedIndex: Int = 0
var body: some View {
TabView(selection: $selectedIndex) {
//script...
}
//...
class LoopingPlayerUIView: UIView {
let myView = ContentView()
if myView.selectedIndex == 0{
player.play()
}
else {
player.pause()
print("pause")
}
}
//...
我尝试通过将myView定义为Contentview(),并通过myView.selectedIndex获取selectedIndex,因为我在其他论坛看到了,但没有成功。
谁能帮我在类中获取selectedIndex?
编辑:以下是完整的类LoopingPlayerUiView:
class LoopingPlayerUIView: UIView {
private let playerLayer = AVPlayerLayer()
private var playerLooper: AVPlayerLooper?
myView=ContentView()
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
// Load the resource
let storage = Storage.storage()
var storageRef = storage.reference().child("User1/pexels-christopher-schultz-5147455-1080x1920-30fps (1).mp4")
storageRef.downloadURL { [self] url, error in
if let error = error {
print(error)
let fileurl = URL(string: "https://i.imgur.com/U52l05s.mp4")!
let asset = AVAsset(url: fileurl)
let item = CachingPlayerItem(asset: asset)
// Setup the player
let player = AVQueuePlayer()
self.playerLayer.player = player
self.playerLayer.videoGravity = .resizeAspectFill
layer.addSublayer(self.playerLayer)
// Create a new player looper with the queue player and template item
playerLooper = AVPlayerLooper(player: player, templateItem: item)
if myView.selectedIndex == 0 && myView.selecfixer == 0{
// Start the movie
player.play()
}
else {
player.pause()
}
} else {
print(url)
let asset = AVAsset(url: url!)
let item = AVPlayerItem(asset: asset)
// Setup the player
let player = AVQueuePlayer()
playerLayer.player = player
playerLayer.videoGravity = .resizeAspectFill
layer.addSublayer(playerLayer)
// Create a new player looper with the queue player and template item
playerLooper = AVPlayerLooper(player: player, templateItem: item)
if selectedIndex == 0 {
player.play()
} else {
player.pause()
print("pause")
}
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
playerLayer.frame = bounds
}
}
1条答案
按热度按时间db2dz4w81#
SwiftUI是这样工作的:
ObservableObject
在阅读答案的其余部分之前,快速检查一下:
LoopingPlayerUIView
真的是UIKit视图吗?以下是如何更好地构建代码的方法: