我正在 swiftUI 中构建一个音乐应用程序。在我的专辑曲目列表视图中,我有专辑的所有曲目,当用户点击专辑曲目时,会播放曲目预览音频,旁边还有一个喜欢的按钮。我想单独切换每个 like 按钮,为此我想我应该创建一个大小为 bool 的数组(轨道数),每个元素都初始化为 false,这将使用 .onTapGesture 更改为 true。但是,这会导致我的预览崩溃,并且不会按我预期的方式运行。我该如何实施?
曲目列表查看代码:
import SwiftUI
import AVFoundation
import AVFAudio
class SoundManager : ObservableObject {
var audioPlayer: AVPlayer?
func playSound(sound: String){
if let url = URL(string: sound) {
self.audioPlayer = AVPlayer(url: url)
}
}
}
struct TracklistView: View {
@StateObject private var tVM = TracklistViewModel()
@StateObject private var soundManager = SoundManager()
@State var nowPlaying = false
@State var isLiked = false
let tracklistDetail: TracklistDetail
var albumCover: String = ""
init(tracklistDetail: TracklistDetail, albumCover: String) {
self.albumCover = albumCover
self.tracklistDetail = tracklistDetail
}
var body: some View {
var arrIsLiked = Array(repeating: false, count: 12)
NavigationStack{
ZStack{
LinearGradient(gradient: Gradient(stops:[Gradient.Stop(color: Color(red:87/255,green:108/255,blue:188/255), location: 0.02),Gradient.Stop(color: Color(red:11/255,green:36/255,blue:71/255), location: 0.30)]), startPoint: .top, endPoint: .bottom).ignoresSafeArea()
VStack{
Text(tracklistDetail.title).font(.title).fontWeight(.semibold).foregroundColor(.white)
ScrollView{
ForEach(tVM.tracklistDetails, id: \.id){ track in
LazyVStack{
//Text("\(track.title)").offset(x:20)
ZStack{
AsyncImage(url: URL(string: albumCover))
.padding(4)
.clipShape(RoundedRectangle(cornerRadius: 20))
.frame(width:330,height:65,alignment:
.leading)
.background(Color(red:25/255,green:108/255,blue:188/255))
.clipShape(RoundedRectangle(cornerRadius: 10))
.onTapGesture {
soundManager.playSound(sound: track.preview)
nowPlaying.toggle()
if nowPlaying{
soundManager.audioPlayer?.play()
} else {
soundManager.audioPlayer?.pause()
}
}
HStack{
// Image(systemName: nowPlaying ? "play":"pause").fontWeight(.heavy)
Text("\(track.title)")
.frame(width:180,height:65,alignment: .leading)
.foregroundColor(Color(red:165/255,green:215/255,blue:232/255)).background(.clear).offset(x:50)
Image(systemName:arrIsLiked[track.trackPosition-1] ? "heart.fill":"heart").offset(x:50)
.fontWeight(.heavy)
.onTapGesture {
arrIsLiked[track.trackPosition-1].toggle()
}
}
}
}
}
}.onAppear(perform: {tVM.fetchTracklist(String(tracklistDetail.id))})
}
}
}
}
}