Сортировка названий песен в табличном представлении - Swift - PullRequest
0 голосов
/ 10 марта 2019

более двух дней я пытаюсь отсортировать это табличное представление по имени, следуя инструкциям и руководствам, но без ответа.Я только узнал учебники с уже созданными значениями в массиве, и это не мой случай.Он должен быть отсортирован в алфавитном порядке от А до Я. Я также пытался использовать некоторые учебники, но они использовали запутанный метод с sortedBy.Может кто-нибудь помочь мне?

import UIKit
import AVFoundation

var audioPlayer = AVAudioPlayer()
var songs:[String] = []
var thisSong = 0
var audioStuffed = false

class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var myTableView: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return songs.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
        cell.textLabel?.text = songs[indexPath.row]
        cell.textLabel?.textColor = UIColor(red:1.00, green:1.00, blue:1.00, alpha:1.0)
        cell.backgroundColor = UIColor(red:0.15, green:0.15, blue:0.34, alpha:1.0)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        do
        {
            let audioPath = Bundle.main.path(forResource: songs[indexPath.row], ofType: ".mp3")
            try audioPlayer = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
            audioPlayer.play()
            thisSong = indexPath.row
            audioStuffed = true
        }
        catch
        {
            print ("ERROR")
        }
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        gettingSongNames()
    }


    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        gettingSongNames()
    }


    //FUNCTION THAT GETS THE NAME OF THE SONGS
    func gettingSongNames()
    {
        let folderURL = URL(fileURLWithPath:Bundle.main.resourcePath!)

        do
        {
            let songPath = try FileManager.default.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)

            //loop through the found urls
            for song in songPath
            {
                var mySong = song.absoluteString

                if mySong.contains(".mp3")
                {
                    let findString = mySong.components(separatedBy: "/")
                    mySong = findString[findString.count-1]
                    mySong = mySong.replacingOccurrences(of: "%20", with: " ")
                    mySong = mySong.replacingOccurrences(of: ".mp3", with: "")
                    songs.append(mySong)

                }

            }

            myTableView.reloadData()
        }
        catch
        {
            print ("ERROR")
        }
    }
}

1 Ответ

3 голосов
/ 10 марта 2019

Почему бы просто не отсортировать массив перед вызовом reloadData in gettingSongNames

songs.sort(by: <)
myTableView.reloadData()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...