簡體   English   中英

點擊 tableViewCell 時的動作 (swift)

[英]Action when tap on tableViewCell (swift)

我想在用戶點擊 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")
}

“test tap cell”沒有出現在控制台中。

您需要設置委托和數據源並正確實現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")
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM