Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

didSelectRowAtIndexPath not being called (Swift)

I've been going in circles for a while and nothing I've found in related posts seems to solve it. I'm programmatically adding a table to a custom UIView. The table and row text displays correctly, but neither didSelectRowAtIndexPath nor willdSelectRowAtIndexPath fire when I run this on the simulator and try to click on any of the rows.

The relevant bits of my code below:

import UIKit
import AVFoundation

@IBDesignable
class PerformanceQuestionView: UIView, UITableViewDelegate, UITableViewDataSource {

var optionsTable = UITableView(frame: CGRectMake(10,200,250,200))

var optionItems = ["One", "Two", "Three", "Four"]

convenience init(rect: CGRect, performanceQuestion:PerformanceQuestion?) {
    self.init(frame: rect)

    NSLog("PerformanceQuestionView.init()")

    self.optionsTable.dataSource = self
    self.optionsTable.delegate   = self
    self.optionsTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    self.optionsTable.allowsSelection   = true
}

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    NSLog("numberOfRowsInSection")
    return optionItems.count
}

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    NSLog("cellForRowAtIndexPath")
    var cell:UITableViewCell = self.optionsTable.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    cell.textLabel.text = self.optionItems[indexPath.row]

    return cell
}

func tableView(tableView: UITableView!, willSelectRowAtIndexPath indexPath: NSIndexPath!) -> NSIndexPath! {
    NSLog("You will select cell #\(indexPath.row)!")
    return indexPath
}

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    NSLog("You selected cell #\(indexPath.row)!")
}

override func layoutSubviews() {

    super.layoutSubviews()

    self.addSubview(optionsTable)
}

}
like image 925
Javier Artiles Avatar asked Sep 18 '14 04:09

Javier Artiles


2 Answers

Removing the TapGestureRecognizer worked for me!!!

    // var backgoroundTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
    // self.view.addGestureRecognizer(backgoroundTap)
like image 114
AAA Avatar answered Oct 17 '22 09:10

AAA


Reason for this could be, you are using a pan gesture in the view. like AAA mentioned removing your pan gesture will do the trick. But if you still want to use the pan gesture you could do the following

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    view.addGestureRecognizer(tap)
    tap.cancelsTouchesInView = false

Making cancelsTouchesInView, false will enable all you taps.

like image 36
Gihan Avatar answered Oct 17 '22 08:10

Gihan