Как добавить или добавить данные в мою таблицу, поскольку она не работает? - PullRequest
0 голосов
/ 13 февраля 2019

Я просто не могу обновить данные в Swift!Я пытаюсь создать приложение для проигрывателя радио для радиостанции друзей, поэтому, когда песня меняется, мне необходимо обновить viewcontroller списка воспроизведения.

Данные из моего Main View Controler являются экземпляром структуры.Я знаю, что данные генерируются и передаются в таблицу, но по какой-то причине массив не обновляется.Я уверен, что это что-то простое.

Я пытался напрямую вводить данные с помощью вызова, используя протокол и используя функцию.Используя протокол и функцию, я могу видеть переданные данные через оператор печати.

class PlaylistVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
    //Mark: Variables ~~~~~~~~~~~~###########################################

    var sourceDatas = [PlaylistData]()

    //Mark: View Containers ~~~~~############################################
    private let bg = GradientBG()
    private let closeButton = UIButton()
    let playlistTable = UITableView()

    //Mark: Overrides ~~~~~~~~~~~~###########################################
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        playlistTable.delegate = self
        playlistTable.dataSource = self

        layoutUI()
        setupTable()
        setupClose()
    }

    //Mark: objc func's ~~~~~~~~~~~###########################################
    @IBAction func handleXButton() {
        dismiss(animated: true, completion: nil)
    }

    func handleMoreInfo(_ playlist: PlaylistData) {
        let vc = SongPopUp()
        vc.buildLables(playlist)

        vc.modalPresentationStyle = .overCurrentContext
        self.present(vc, animated: true, completion: nil )
    }
    //##################################################################  
    //Mark: Pass Data ##################################################  
    //Mark: Not Working!! ##############################################  
    //##################################################################      
    func handlePlaylist(_ with: PlaylistData) {
        print(with)
        sourceDatas.append(with)
        //sourceDatas.insert(with, at: 0)
        playlistTable.reloadData()
    }

    //Mark: Table view   ################################################
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sourceDatas.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = UITableViewCell(style: .subtitle, reuseIdentifier: "myCell")

        cell.backgroundColor = .clear
        cell.selectionStyle = .none

        tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)

        if let text = cell.textLabel {
            components.layoutHeadingLable(sender: text, title: sourceDatas[indexPath.row].heading, size: 20)
        }
        if let dtext = cell.detailTextLabel {
            components.layoutSubheadingLable(sender: dtext, title: sourceDatas[indexPath.row].subheading, size: 14)
        }

        if sourceDatas[indexPath.item].hasStoreLink {
            cell.accessoryType = .detailButton
            cell.tintColor = .white
        }

        return cell
    }

    func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath)  {
        let dataToPass = self.sourceDatas[indexPath.row]
        print("Extended~~~~~~~~~~~~~~~~~~~~")
        print(dataToPass)
        handleMoreInfo(sourceDatas[indexPath.row])
    }

    //Mark: Setup Table ~~~~~~~~~~~~~~###########################################
    func setupTable() {
        playlistTable.backgroundColor = .clear
        playlistTable.separatorStyle = .singleLine
        playlistTable.rowHeight = 45
        playlistTable.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
    }

......

1 Ответ

0 голосов
/ 14 февраля 2019

Я думаю, что-то не так с вашим cellForRowAt

Сначала попробуйте упростить задачу, например:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! UITableViewCell
        cell.textLabel?.text = sourceDatas[indexPath.row]

        return cell
    }

Посмотрите, сможете ли вы найти добавленный объект.Затем погрузитесь в подробные настройки вашей клетки.

...