Edward Hung Edward Hung - 3 months ago 5x
Swift Question

pass argument in selector for scheduleTimerwithTimeInterval

In swift, I have a uitableviewCell that has double tap and single tap implemented. The double tap works. However, I am having a bit of trouble with single tap. Due to the present of double tap, I implemented single tap with a timer. The following code successfully prints out "Single Tapped"

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

var now = NSDate().timeIntervalSince1970

if (now - lastClick < 0.3) && indexPath.isEqual(lastIndexPath) {
// Double tapped on cell
if let cell = discoverTableView.cellForRowAtIndexPath(indexPath) as? CommentCell {
cell.doubleTapCellActive({ (addBumpStatus, success) in

} else {
singleTapTimer = NSTimer.scheduledTimerWithTimeInterval(0.31, target: self, selector: #selector(DiscoverVC.singleTapped), userInfo: nil, repeats: false)
lastClick = now
lastIndexPath = indexPath

func singleTapped() {
print("Single tapped")

However, the problem is, I want the single tap to know which index path was selected. I tried doing something like

func singleTapped(indexPath: NSIndexPath) {}

But this gives me an error as selector does not like this syntax. Is there a way to make the selector work or a better way of doing it?



The usual way is to implement the action with the NSTimer parameter

func singleTapped(timer : NSTimer) {
   print("Single tapped", timer.userInfo!["indexPath"] as! NSIndexPath)

and pass custom data via the userInfo property of the timer for example

singleTapTimer = NSTimer.scheduledTimerWithTimeInterval(0.31, 
                         target: self, 
                         selector: #selector(singleTapped(_:)), 
                         userInfo: ["indexPath":indexPath], 
                         repeats: false)