Допустим, у меня есть представление контейнера, а внутри него - представление пользовательского интерфейса (представление альбома категорий), табличное представление для предоставления источника данных для этого представления пользовательского интерфейса.
Проблема заключается в том, что при нажатии кнопкиВ строке «Представление альбома категории» не открывается следующий табличный вид, который называется «Имя альбома».Я использую segue id / prepare()
для передачи, я проверяю свой код, segue установлен в prepare()
в коде, а также в раскадровке.Любые комментарии / подсказки приветствуются!
/// Мой код, как показано ниже,
/ / / обновите мой код, какКомментарий Вадиана, комментирующий tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
действительно исправляет проблему.
CategoryAlbumView.swift
import UIKit
import AVKit
class CategoryAlbumView: UIViewController {
var directoryContents = [URL]()
var songName: String?
var artistName: String?
var albumName: String?
var albumArtwork: UIImage?
var tableData = [SongData]()
var albumArray = [String]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.retrieveSongsfromLocalDir()
var seen = Set<String>()
var unique = [SongData]()
for message in tableData {
if !seen.contains(message.albumName) {
unique.append(message)
seen.insert(message.albumName)
}
}
// convert Set to Array
albumArray = Array(seen)
print("seen count", seen.count)
// let testArray = tableData.filter { $0.albumName == "Beauty In The Mundane"}
// print("TestArray count", testArray.count)
// refresh table data.
tableView.reloadData()
}
func retrieveSongsfromLocalDir() {
do {
tableData.removeAll()
// Get the document directory url
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// Get the directory contents urls (including subfolders urls)
directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
// if you want to filter the directory contents you can do like this:
let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
// get music metadata (artist, album)
for url in mp3Files {
let asset = AVAsset(url: url)
let metaData = asset.metadata
// to use url's name for song name to avoid there is no metaData info for songs.
let songTitle = url.deletingPathExtension().lastPathComponent
if songTitle != "" {
songName = songTitle
} else {
songName = "Unknown Song"
}
if let artist = metaData.first(where: {$0.commonKey == .commonKeyArtist}), let value = artist.value as? String {
artistName = value
} else {
artistName = "Unknown Artist"
}
if let album = metaData.first(where: {$0.commonKey == .commonKeyAlbumName}), let value = album.value as? String {
albumName = value
// print("Album:",albumName)
} else {
albumName = "Unknown Album"
}
if let albumImage = metaData.first(where: {$0.commonKey == .commonKeyArtwork}), let value = albumImage.value as? Data {
albumArtwork = UIImage(data: value)
} else {
albumArtwork = UIImage(named: "Album-50")
print("artWork is not found!")
}
tableData.append(SongData(songName: songName!, artistName: artistName!, albumName: albumName!, albumArtwork: albumArtwork!, url: url))
}
} catch {
print(error)
}
}
}
extension CategoryAlbumView: UITableViewDelegate {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "CategoryAlbumSongs":
if let indexPath = self.tableView.indexPathForSelectedRow {
let controller = segue.destination as! CategoryAlbumSongs
let cellText = albumArray[indexPath.row]
print("Prepare ========= Prepare ")
controller.albumSongs = tableData.filter { $0.albumName == cellText}
}
default: break
}
}
}
// MARK: - UITableViewDataSource
extension CategoryAlbumView: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return albumArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = albumArray[indexPath.row]
cell.imageView?.image = UIImage(named: "Album-50")
return cell
}
}
/ / / * CategoryAlbumSongs.swift
import UIKit
class CategoryAlbumSongs: UITableViewController {
var albumSongs = [SongData]()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return albumSongs.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = albumSongs[indexPath.row].songName
cell.detailTextLabel?.text = albumSongs[indexPath.row].artistName
cell.imageView?.image = albumSongs[indexPath.row].albumArtwork
return cell
}
}