Dilip Jangid
Dilip Jangid

Reputation: 774

didSelectRowAt method not invoked (swift 3)

I created a simple TableView example Programatically.

import UIKit

class ViewController: UIViewController
{
    var solarObjects : UITableView! = nil
    var dataSourceTable:DemoTable?

    override func viewDidLoad()
    {
        super.viewDidLoad()

        solarObjects = UITableView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height * 0.9))
        solarObjects.allowsSelection = true
        solarObjects.backgroundColor = UIColor.white
        self.dataSourceTable = DemoTable()
        self.solarObjects.dataSource = self.dataSourceTable

        view.addSubview(solarObjects)
    }
    override func didReceiveMemoryWarning() 
    {
        super.didReceiveMemoryWarning()
    }
}

And Data Source for the solarObject is in separate file (DemoTable.swift)

import Foundation
import UIKit

class DemoTable: UITableViewController
{
    var arr_SolarObjects = ["SUN", "MOON", "STAR"]

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr_SolarObjects.count
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        print("A SolarObject is selected")
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
            cell?.frame(forAlignmentRect: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 30))
        }

        cell?.textLabel?.text = arr_SolarObjects[indexPath.row]

        return cell!
    }
}

This sample is running perfectly but when i select a row the didSelectRowAt method is not respond ->(print("A SolarObject is selected")), So how to handle action on a row selection? Help will be appreciated :-)

Upvotes: 0

Views: 173

Answers (2)

Punit
Punit

Reputation: 1340

Add this line in your viewController

var dataDelegateTable:DemoTable?

Then in viewDidLoad add: self.solarObjects.delegate = self.dataDelegateTable

Upvotes: 0

mhergon
mhergon

Reputation: 1678

You need to add...

self.solarObjects.delegate = self.dataSourceTable

didSelectRow is part from UITableViewDelegate

Upvotes: 2

Related Questions