gpt4 book ai didi

ios - 如何在 SwiftUI 列表中显示 MPMediaItem 图稿?

转载 作者:行者123 更新时间:2023-11-28 07:20:14 30 4
gpt4 key购买 nike

我尝试在我的 iPhone 上构建一个包含所有本地存储歌曲的 SwiftUI 列表。我使用 Apple 的 MediaPlayer Framework 获取歌曲并将它们存储在 EnvironmentObject 中,以便在我的 SwiftUI View 中轻松访问。

在我的 Cell 中,我通过以下方式访问图像,但我得到的只是一个白色的 50x50 block :

Image(uiImage: self.item.artwork!.image(at: CGSize(width: 50, height: 50))!)

结果:https://i.imgur.com/gulvJ8u.png

// EnvironmentObject
class UserData: ObservableObject {

@Published var allowMusicLibraryAccess: Bool = false
@Published var songs: [MPMediaItem]

init() {
self.songs = [MPMediaItem]()

self.initAllowMusicLibraryAccess()
}

private func initAllowMusicLibraryAccess() -> Void {
MPMediaLibrary.requestAuthorization { status in
if status == .authorized {
DispatchQueue.main.async {
self.allowMusicLibraryAccess = true
self.songs = MPMediaQuery.songs().items!
}
}
}
}
}
// List
struct ContentView: View {

@EnvironmentObject var userData: UserData

var body: some View {
ZStack() {
if self.userData.allowMusicLibraryAccess {
NavigationView {
List {
ForEach(self.userData.songs, id: \.persistentID) { song in
SongCell(song)
}
}
.navigationBarTitle("Songs")
}
} else {
Text("Music Library Access needed")
}
}
}
}
// Cell
struct SongCell: View {

let item: MPMediaItem

init(_ item: MPMediaItem) {
self.item = item
}

var body: some View {

Button(action: {
print("clicked \(self.item)")
}) {
HStack() {
if self.item.artwork != nil {
Image(uiImage: self.item.artwork!.image(at: CGSize(width: 50, height: 50))!)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(4)
}

VStack(alignment: .leading) {
Text(self.item.title ?? "---")

Text(self.item.artist ?? "---")
.font(.system(.footnote))
.opacity(0.7)
}
}
}
.frame(minWidth: nil, idealWidth: nil, maxWidth: .infinity, minHeight: 55, idealHeight: 55, maxHeight: 55, alignment: .leading)
}
}

最佳答案

解决方案是使用 .renderingMode() 修饰符:

Image(uiImage: self.item.artwork!.image(at: CGSize(width: 50, height: 50))!)
.renderingMode(.original)

关于ios - 如何在 SwiftUI 列表中显示 MPMediaItem 图稿?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58435382/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com