teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

3

selectionStyle についてのコードを追加

2017/09/22 01:17

投稿

ykws
ykws

スコア1242

answer CHANGED
@@ -6,10 +6,21 @@
6
6
  他にも考え方はあるので参考の一つとしてください。
7
7
 
8
8
  ```swift
9
+ override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
10
+ let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
11
+ cell.textLabel?.text = Haru[indexPath.row]
12
+ cell.selectionStyle = (Haru.count > (indexPath.row + 1)) ? .none : .blue
13
+ return cell
14
+ }
15
+
9
16
  override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
10
17
  if Haru.count > (indexPath.row + 1) {
11
18
  return nil
12
19
  }
13
20
  return indexPath
14
21
  }
15
- ```
22
+ ```
23
+
24
+ ### 参考
25
+
26
+ [UITableViewのセルを選択不可にする方法](https://qiita.com/takashings/items/36b820f09fb19edd7556)

2

willSelectRowAt メソッド中への記載を明記

2017/09/22 01:17

投稿

ykws
ykws

スコア1242

answer CHANGED
@@ -6,9 +6,10 @@
6
6
  他にも考え方はあるので参考の一つとしてください。
7
7
 
8
8
  ```swift
9
+ override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
9
- if Haru.count > (indexPath.row + 1) {
10
+ if Haru.count > (indexPath.row + 1) {
10
- return nil
11
+ return nil
12
+ }
13
+ return indexPath
11
14
  }
12
-
13
- return indexPath
14
15
  ```

1

一番下のセルであることに注目した判定方法を追記

2017/09/21 06:14

投稿

ykws
ykws

スコア1242

answer CHANGED
@@ -1,3 +1,14 @@
1
1
  @fuzzball さんの回答を補足すると、 `indexPath` に選択したセルの位置が渡されるので、選択させたくないセルの位置だったら `nil` を返す。そうでない場合は、 `indexPath` をそのまま返すようにします。
2
2
 
3
- [IndexPath](https://developer.apple.com/documentation/foundation/indexpath) には `section` と `row` があって、今回 `section` は一つしかないので、`indexPath.row` がセルの位置と等しくなっています。
3
+ [IndexPath](https://developer.apple.com/documentation/foundation/indexpath) には `section` と `row` があって、今回 `section` は一つしかないので、`indexPath.row` がセルの位置と等しくなっています。
4
+
5
+ 今回のコードだと、 **一番下のセル** が反応してほしくないので次のように判定する方法があります。
6
+ 他にも考え方はあるので参考の一つとしてください。
7
+
8
+ ```swift
9
+ if Haru.count > (indexPath.row + 1) {
10
+ return nil
11
+ }
12
+
13
+ return indexPath
14
+ ```