【问题标题】:func tableview didSelectRowAtIndexPath is not called [duplicate]func tableview didSelectRowAtIndexPath 未被调用[重复]
【发布时间】:2017-04-11 21:50:30
【问题描述】:

当用户单击单元格时我试图调用viewModel.userDidSelectItem(identifier: "DetailMainViewController") 函数但我无法调用,首先print(indexPath.row) 为零,其次我不知道它是否正确调用。

import Foundation
import UIKit

class MainViewController: UIViewController, UITableViewDataSource {

    @IBOutlet var tableview:UITableView!
    var viewModel: MainViewModel = MainViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel.loadUsers {
            self.tableview?.reloadData()
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.fakeUsers?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "fakeUserObjectCell") as! MainTableViewCell
        cell.fakeUserObject = viewModel.fakeUsers?[(indexPath as NSIndexPath).row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

       print(indexPath.row)
       viewModel.userDidSelectItem(identifier: "DetailMainViewController")
    }
}

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    当您使用 tableview 时,您需要将 UITableViewDataSourceUITableViewDelegate 设置为 MainViewController。 并覆盖下面的函数

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

    【讨论】:

    • 你不需要覆盖numberOfSections(:)
    • 如果这与问题有关,则不会有任何单元格可供选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    相关资源
    最近更新 更多