swiftuitableviewswift2tvos

Perform action when UITableViewCell is clicked


I am making an tvOS app for the Apple TV but I have some problems with my UITableView. When I click on a UITableViewCell nothing happens. I am using targetForAction but it doesn't seem to work.

This is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.dataSource = self
    self.tableView.delegate = self
}

let allData = ["Los Angeles","New York","San Fransisco"]

@IBOutlet weak var tableView: UITableView!

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

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .Default, reuseIdentifier: nil)
    cell.textLabel?.text = "\(allData[indexPath.row])"
    cell.targetForAction("buttonClicked:", withSender: self)
    return cell
}

func buttonClicked(sender:AnyObject) {
    print("button clicked!")
}

Solution

  • I found the solution. I had to add this function:

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("selected cell \(indexPath.row)")
    }