Действие при нажатии на tableViewCell (swift) - PullRequest
0 голосов
/ 16 февраля 2020

Я хочу выполнить код, когда пользователь нажимает на tableViewCell, это код:

import UIKit
import MediaPlayer

class ViewController: UIViewController, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titolo.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
    let text1 = titolo[indexPath.row]
    let text2 = genere[indexPath.row]
    cell.textLabel?.text = text1
    cell.detailTextLabel?.text = text2
    return cell
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("test tap cell")
}

@IBOutlet weak var tableView: UITableView!

let mediaItems = MPMediaQuery.songs().items
let musicPlayer = MPMusicPlayerApplicationController.applicationQueuePlayer

...

Эта функция не работает:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("test tap cell")
}

«ячейка тестового касания» не появляется в консоли.

1 Ответ

0 голосов
/ 16 февраля 2020

Вам необходимо установить делегат и источник данных и правильно реализовать didSelectRowAt

class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.tableView.delegate = self
        self.tableView.dataSource = self

    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titolo.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
        cell.textLabel?.text = text1
        cell.detailTextLabel?.text = text2
        return cell
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
         print("test tap cell")
    }
}
...