【问题标题】:pass argument in selector for scheduleTimerwithTimeInterval在 scheduleTimerwithTimeInterval 的选择器中传递参数
【发布时间】:2016-07-12 19:34:05
【问题描述】:

在 swift 中,我有一个 uitableviewCell 实现了双击和单击。双击有效。但是,我在单击时遇到了一些麻烦。由于双击的存在,我用计时器实现了单击。以下代码成功打印出“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
            })
        }
        singleTapTimer?.invalidate()

    } 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")
}

但是,问题是,我希望单击即可知道选择了哪个索引路径。我尝试做类似

#selector(DiscoverVC.singleTapped(_:indexPath))
func singleTapped(indexPath: NSIndexPath) {}

但这给了我一个错误,因为选择器不喜欢这种语法。有没有办法让选择器工作或更好的方法?

谢谢,

【问题讨论】:

  • 为什么要使用 NSTimer 进行双击?你也可以使用手势。
  • 我在表格中只有三个标签,我不认为您可以向单元格添加手势?我不想为单元格内的所有内容添加手势

标签: ios objective-c swift selector


【解决方案1】:

通常的方式是用NSTimer参数实现动作

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

并通过计时器的userInfo 属性传递自定义数据,例如

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

【讨论】:

  • 似乎是要走的路。但是当我试图检索 timer.userInfo 时! NSIndexPath,我遇到了一些 EXC_BAD_ACCESS(code= 1, address= 0x18) 错误。我什至将选择器更改为“singleTapped:”只是为了确保可以传递参数
  • 我的例子应该可以工作。我将userInfo 参数指定为字典。
  • 现在工作。多谢了。计时器失效后,我试图获取 userInfo 。这是禁止的。
猜你喜欢
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 2012-08-31
相关资源
最近更新 更多