Last active
January 16, 2018 06:16
-
-
Save takashi1975/64b9db6da1a9a707d88741fb33817d9a to your computer and use it in GitHub Desktop.
UITableViewCell をタップしている間だけ選択状態にしたい (指を離したら解除)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * UITableViewController を継承している場合を想定した例 | |
| */ | |
| extension xxxTableViewController { | |
| override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
| //セルの作成 | |
| let cell = UITableViewCell(style: .value1, reuseIdentifier: "cell") | |
| //Configure the cell... | |
| //指を離したときに .selectionStyle を元に戻したい | |
| if (true) { | |
| // https://qiita.com/taketomato/items/e0e45f0d768109abef2f | |
| let gesture = UILongPressGestureRecognizer(target: self, action: #selector(tapCell(_:))) | |
| gesture.minimumPressDuration = 0 | |
| cell.addGestureRecognizer(gesture) | |
| } | |
| return cell | |
| } | |
| override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { | |
| //TODO: 該当するCELLのみ (例: IndexPath(0,0)) | |
| switch indexPath.section { | |
| case 0: | |
| switch indexPath.row { | |
| case 0: | |
| return indexPath | |
| default: | |
| break; | |
| } | |
| break; | |
| default: | |
| break; | |
| } | |
| return nil | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * UITableViewController を継承している場合を想定した例 | |
| */ | |
| extension xxxTableViewController { | |
| //セルをタップ | |
| @objc fileprivate func tapCell(_ sendor: UILongPressGestureRecognizer) { | |
| switch sendor.state { | |
| case .began, .ended: | |
| //print(sendor.view) | |
| if let cell = sendor.view as? UITableViewCell { | |
| if let indexPath = self.tableView.indexPath(for: cell) { | |
| //選択時のアニメーション | |
| if (sendor.state == .began) { | |
| self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) | |
| } else { | |
| self.tableView.deselectRow(at: indexPath, animated: true) | |
| } | |
| } | |
| } | |
| break | |
| default: | |
| break | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
StoryBoard の UITableView の設定で Selection : SingleSelection と設定していることを想定