【问题标题】:Action when tap on tableViewCell (swift)点击 tableViewCell 时的动作(swift)
【发布时间】:2020-05-31 07:01:47
【问题描述】:

我想在用户点击 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”没有出现在控制台中。

【问题讨论】:

  • 点击时单元格是否会突出显示?还要确保您的 viewcontroller 实例设置为 tableview 的委托

标签: swift xcode uitableview iso


【解决方案1】:

需要设置delegate和dataSource并正确实现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")
    }
}

【讨论】:

  • 它现在可以工作了:我添加了“UITableViewDelegate”并将“didSelectRowAtIndexPath indexPath: NSIndexPath”替换为“didSelectRowAt indexPath:IndexPath”。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
相关资源
最近更新 更多