-4

I want to select a row of UITableView with override of the follow function:

class table:  NSObject, UITableViewDelegate, UITableViewDataSource{
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
            print("NEVER")  
        }
    }
}

but never show the print, why? what is the wrong in my code?

class OtherClass: UIViewController {
    var table = Table()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let mtv = UITableView()
        mtv.dataSource = table
        mtv.delegate = table

        view.addSubview(mtv)
    }
}

for more information :

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell  = UITableViewCell()

        tableView.register(newCell.self, forCellReuseIdentifier:"newCell");
        cell =  tableView.dequeueReusableCell(withIdentifier: "newCell", for: indexPath) as! newCell
        cell.accessoryType = .disclosureIndicator;

        return  cell
    }
}
Olympiloutre
  • 1,837
  • 2
  • 21
  • 33
becauseR
  • 39
  • 7

1 Answers1

-1

try this:

import UIKit

class ViewController: UIViewController {

    let cellID = "cellIdentifier"
    let table = Table()

    override func viewDidLoad() {
        super.viewDidLoad()

        let tableView = UITableView(frame: UIScreen.main.bounds, style: UITableView.Style.plain)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
        tableView.delegate = table
        tableView.dataSource = table
        view.addSubview(tableView)
    }
}

class Table: NSObject, UITableViewDelegate, UITableViewDataSource {
    let cellID = "cellIdentifier"

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You selected: \(indexPath.row)!")
    }
}

I didn't see enough details,so I just build one.

Lynx
  • 183
  • 10
  • i edited my question, the datasource is working because i see the table, but never enters in this function didSelectRowAtIndexPath – becauseR Oct 09 '19 at 01:54
  • @becauseR Counld you show the code which is about tableview like `func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell`?And it's not suitable to create UITableView in `viewWillAppear`.It will be better to create it in viewDidLoad. – Lynx Oct 09 '19 at 02:41
  • @becauseR Have you tried to add frame?I have no idea why it will work since you didn't set the frame of UITableView...And the code I post works well.So maybe you can try what I do. – Lynx Oct 09 '19 at 06:07