LoginSignup
55
61

More than 5 years have passed since last update.

【swift】 UITableViewで長押ししたセルのindexPath.rowを取得する方法

Last updated at Posted at 2015-05-24

TableViewのセルをタップした際は、
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
で問題なくindexPathを取得できます。

しかし長押し(UILongPressGestureRecognizer利用)したセルのindexPathを取得する方法は簡単には行かなかったので、その方法を共有します。

まずは、UILongPressGestureRecognizerをtableViewに設定。

  • 長押しされた際、cellLongPressed:メソッドでイベントを受け取ります。
  • tableViewにlongPressGestureRecognizerをaddする。
swift
// UILongPressGestureRecognizer宣言
var longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "cellLongPressed:")

// `UIGestureRecognizerDelegate`を設定するのをお忘れなく
longPressRecognizer.delegate = self

// tableViewにrecognizerを設定
tableView.addGestureRecognizer(longPressRecognizer)

長押ししたセルのindexPath.rowを取得。

  • 長押しした位置からcellのindexPathを取得。

下記のprintln("長押しされたcellのindexPath:\(indexPath?.row)")
indexPath?.rowを取得できます。

swift
/* 長押しした際に呼ばれるメソッド */
func cellLongPressed(recognizer: UILongPressGestureRecognizer) {

        // 押された位置でcellのPathを取得
        let point = recognizer.locationInView(tableView)
        let indexPath = tableView.indexPathForRowAtPoint(point)

        if indexPath == nil {

        } else if recognizer.state == UIGestureRecognizerState.Began  {
            // 長押しされた場合の処理
            println("長押しされたcellのindexPath:\(indexPath?.row)")
         }
    }

参考

下記の記事を参考に「swift」で書き直しました。
http://iritec.jp/iphone/848/

55
61
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
55
61