2016-06-12 5 views
2

私はcellForRowAtIndexPathtableViewCellでtapとlongPressの両方を処理する方法は?

let longPress = UILongPressGestureRecognizer(target: self, action: #selector(CalorieCountViewController.handleLongPress)) 
cell.addGestureRecognizer(longPress) 
longPress.cancelsTouchesInView = true 
let tapPress = UITapGestureRecognizer(target: self, action: #selector(CalorieCountViewController.handleTapPress)) 
cell.addGestureRecognizer(tapPress) 
tapPress.cancelsTouchesInView = true 

でこれを入れて外これら(以下コード)を入れ、完全didSelectRowAtIndexPath機能を除去し、単に選択された行ユーザ取得する代わりindexPathForSelectedRow使用。

func handleLongPress(sender: UILongPressGestureRecognizer){ 
    let index = tableView.indexPathForSelectedRow! 
    doSomething(index) 
} 

func handleTapPress(sender: UITapGestureRecognizer){ 
    let index = tableView.indexPathForSelectedRow! 
    doSomethingElse(index) 
} 

はindexPathForSelectedRowがnilを返すが判明したが、私は、行を選択しなかったし、何の「deselectRowAtIndexPathは」どこにでも私のコードではありません。

+0

ですUITableViewの "didSelectRowAtIndexPath"デリゲートメソッドを使用する –

答えて

8

UILongPressGestureRecognizerCellに追加しないでください。代わりにUITapGestureRecognizer使用didSelectRowAtIndexPath

func handleLongPress(sender: UILongPressGestureRecognizer){ 
    if longPressGestureRecognizer.state == UIGestureRecognizerState.Began { 
     let touchPoint = longPressGestureRecognizer.locationInView(yourTableView) 
     if let indexPath = yourTableView.indexPathForRowAtPoint(touchPoint) { 
     // your code here, get the row for the indexPath or do whatever you want 
     } 
    } 
} 

に触れセルインデックスを取得します

let longPress = UILongPressGestureRecognizer(target: self, action: #selector(CalorieCountViewController.handleLongPress)) 
yourTableView.addGestureRecognizer(longPress) 
viewDidLoadUITableViewにそれを追加するだけのことができますUITableViewCellの上で長押しジェスチャーを追加し、タップのためのより良い方法

関連する問題