Reputation: 1365
I have created a component in XIB
file. This file includes 2 components
I have then linked and set it's File's Owner
class to SampleView
. I have attached the XIB file view
with SampleView.swift file and this file have only following code in it's class:
@IBOutlet var view: UIView!
I have now created a controller file SampleController
with protocols UIViewController
, UITableViewDelegate
and UITableViewDataSource
. I have placed the following code in it's init()
func to display the custom component:
init() {
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = UIModalPresentationStyle.Custom
view.addSubview(SampleView())
}
I am using this SampleController
to programmatically display as a Modal
.
These codes does display as the Modal showing Label and TableView. It also populates the data in TableView. The problem is:
When I tap the cell in table, it doesn't trigger the event on first attempt. When I tap another cell then it trigger the previous cell event.
Any idea why is this happening?
Here are 2 functions used for populating and handling cell tap:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CELL")
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CELL")
}
cell!.textLabel?.text = sampleData[indexPath.row]["title"]
return cell
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
print("tapped")
}
Upvotes: 1
Views: 1240
Reputation: 1365
Darn it! I was using didDeselectRowAtIndexPath
instead of didSelectRowAtIndexPath
. That's what will happen when you are programming after midnight.
Upvotes: 3
Reputation: 17622
You need to use a different method to dequeue the cell:
var cell = tableView.dequeueReusableCellWithIdentifier("CELL", forIndexPath: indexPath)
The check for a nil cell is unnecessary, by the way.
Upvotes: 0