質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1801閲覧

collectionView セル選択時に色を変える

tsuji71

総合スコア17

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2020/05/17 04:49

作りたいもの
collectionViewを使ってカードゲームのようなものを作っています

実現したいこと
collectionViewのCell(カードの表示ように使っている)をタップした際に、選択しているCellの色が変わるようにしたいのですがうまくいきません(触れている時のみに色が変化している状態でも、次のCellを選択するまで色が変わった状態でもどちらでも構いません)

試したこと
いくつかの記事を参考に

swift

1 func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: IndexPath) { 2 if collectionView == myCollectionView { 3 let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) 4 cell.backgroundColor = UIColor.red 5 } else { 6 let cell = enemyCollectionView.dequeueReusableCell(withReuseIdentifier: "NCell", for: indexPath) 7 cell.backgroundColor = UIColor.red 8 } 9 10 }

のように書いてみましたが、セルをタップしてみても色は変わりませんでした

どのようにすればうまくいくのか教えていただきたいです

こちらは、collectionViewに関係のなさそうなものを省いたコードです

swift

1コード 2// 3// ViewController.swift 4// GuessNum 5// 6// Created by Apple on 2020/05/08. 7// Copyright © 2020 ryotaro.tsuji. All rights reserved. 8// 9 10import UIKit 11 12class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { 13 14 15 //  CollectionViewの接続 16 @IBOutlet weak var myCollectionView: UICollectionView! 17 @IBOutlet weak var enemyCollectionView: UICollectionView! 18 @IBOutlet weak var enemyGuessButton: UIButton! 19 20 21 // 山札の配列 22 var numArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] 23 // 味方札の配列 24 var myNumArray:[Int] = [] 25 // 敵札の配列 26 var enemyNumArray:[Int] = [] 27 // ターンのカウント 28 var addTurnCount = 0 29 var checkTurnCount = 0 30 var forCheckCount = 0 31 // TextField 32 @IBOutlet weak var myTextField: UITextField! 33 @IBOutlet weak var enemyTextField: UITextField! 34 // CollectionView表示用の数字 35 var myCellSetNum = 0 36 var enemyCellSetNum = 0 37 // タップしたセルの値 38 var tapedCellNum = 0 39 // 的中した数字の配列 40 var hitNumArray:[Int] = [] 41 42 43 44 45 override func viewDidLoad() { 46 super.viewDidLoad() 47 48 49 self.view.backgroundColor = UIColor(red: 0, green: 0.7, blue: 0, alpha: 1) 50 51 52 // 山札をシャッフル 53 numArray.shuffle() 54 55 56 // CollectionViewのdelegate 57 myCollectionView.delegate = self 58 myCollectionView.dataSource = self 59 enemyCollectionView.delegate = self 60 enemyCollectionView.dataSource = self 61 62 // CollectionViewのレイアウト 63 let mylayout = UICollectionViewFlowLayout() 64 mylayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) 65 mylayout.minimumInteritemSpacing = 1 66 mylayout.minimumLineSpacing = 1 67 myCollectionView.collectionViewLayout = mylayout 68 69 70 let enemyLayout = UICollectionViewFlowLayout() 71 enemyLayout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) 72 enemyLayout.minimumInteritemSpacing = 1 73 enemyLayout.minimumLineSpacing = 1 74 enemyCollectionView.collectionViewLayout = enemyLayout 75 76 // collectionViewの背景画像 77 78 self.myCollectionView.backgroundColor = UIColor(red: 0, green: 0.7, blue: 0, alpha: 1) 79 self.enemyCollectionView.backgroundColor = UIColor(red: 0, green: 0.7, blue: 0, alpha: 1) 80 } 81 82 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 83 84 if collectionView == myCollectionView { 85 return myNumArray.count 86 } else if collectionView == enemyCollectionView { 87 return enemyNumArray.count 88 } else { 89 return 0 90 } 91 } 92 93 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 94 95 if collectionView == self.myCollectionView { 96 let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) 97 98 let label = cell.contentView.viewWithTag(1) as! UILabel 99 myCellSetNum = myNumArray[indexPath.row] 100 101 102 let evenOrOdd = myCellSetNum % 2 103 switch evenOrOdd { 104 case 0: 105 106 label.textColor = UIColor.white 107 cell.backgroundColor = UIColor.black 108 case 1: 109 110 label.textColor = UIColor.black 111 cell.backgroundColor = UIColor.white 112 default: 113 label.text = "?" 114 } 115 116 117 let checkCellNum = hitNumArray.firstIndex(of: myNumArray[indexPath.row]) 118 119 if checkTurnCount == 1 { 120 let evenOrOdd = myCellSetNum % 2 121 switch evenOrOdd { 122 case 0: 123 let myCellSetString = "(myCellSetNum / 2)" 124 label.text = myCellSetString 125 126 case 1: 127 let myCellSetString = "((myCellSetNum + 1) / 2)" 128 label.text = myCellSetString 129 130 default: 131 label.text = "?" 132 } 133 134 } else { 135 if let no = checkCellNum { 136 137 let evenOrOdd = myCellSetNum % 2 138 switch evenOrOdd { 139 case 0: 140 let myCellSetString = "(myCellSetNum / 2)" 141 label.text = myCellSetString 142 143 case 1: 144 let myCellSetString = "((myCellSetNum + 1) / 2)" 145 label.text = myCellSetString 146 147 default: 148 label.text = "?" 149 } 150 151 } else { 152 let label = cell.contentView.viewWithTag(1) as! UILabel 153 label.text = "?" 154 } 155 } 156 print(myCellSetNum) 157 return cell 158 159 } else { 160 let cell = enemyCollectionView.dequeueReusableCell(withReuseIdentifier: "NCell", for: indexPath) 161 162 let label = cell.contentView.viewWithTag(1) as! UILabel 163 enemyCellSetNum = enemyNumArray[indexPath.row] 164 let evenOrOdd = enemyCellSetNum % 2 165 switch evenOrOdd { 166 case 0: 167 168 label.textColor = UIColor.white 169 cell.backgroundColor = UIColor.black 170 case 1: 171 172 label.textColor = UIColor.black 173 cell.backgroundColor = UIColor.white 174 default: 175 label.text = "?" 176 } 177 178 179 let checkCellNum = hitNumArray.firstIndex(of: enemyNumArray[indexPath.row]) 180 181 if checkTurnCount == 2 { 182 let evenOrOdd = enemyCellSetNum % 2 183 switch evenOrOdd { 184 case 0: 185 let myCellSetString = "(enemyCellSetNum / 2)" 186 label.text = myCellSetString 187 188 case 1: 189 let enemyCellSetString = "((enemyCellSetNum + 1) / 2)" 190 label.text = enemyCellSetString 191 192 default: 193 label.text = "?" 194 } 195 } else { 196 if let no = checkCellNum { 197 198 let evenOrOdd = enemyCellSetNum % 2 199 switch evenOrOdd { 200 case 0: 201 let myCellSetString = "(enemyCellSetNum / 2)" 202 label.text = myCellSetString 203 204 case 1: 205 let enemyCellSetString = "((enemyCellSetNum + 1) / 2)" 206 label.text = enemyCellSetString 207 208 default: 209 label.text = "?" 210 } 211 } else { 212 let label = cell.contentView.viewWithTag(1) as! UILabel 213 label.text = "?" 214 } 215 } 216 return cell 217 218 } 219 220 } 221 222 223 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 224 225 if collectionView == self.myCollectionView { 226 tapedCellNum = myNumArray[indexPath.row] 227 228 } else { 229 tapedCellNum = enemyNumArray[indexPath.row] 230 231 } 232 print(tapedCellNum) 233 } 234 235 236 // セルのレイアウトを設定 237 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 238 239 let width = UIScreen.main.bounds.size.width 240 241 let widthcellSize : CGFloat = (width - 11) / 14 242 let heightcellSize : CGFloat = widthcellSize * 2 243 return CGSize(width: widthcellSize, height: heightcellSize) 244 } 245 246 247 } 248 249 250 251

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

イメージ説明

CellForItemAtn内でUICollectionViewselectedBackgroundViewに用意したカスタムViewを突っ込んで、
UICollectionViewのallowSelection/allowsMultipleSelectionプロパティを設定してあげれば、あとは何も記述しなくともよしなにやってくれます。

私はこの方法が良いと思います。

swift

1import UIKit 2 3// 背景用のView 4class CellBgView: UIView { 5 6 init(num: Int) { 7 super.init(frame: CGRect.zero) 8 // 偶数と奇数で色変えてみよう 9 backgroundColor = num % 2 == 0 ? .red : .orange 10 } 11 12 required init(coder aDecoder: NSCoder) { 13 fatalError("init(coder:) has not been implemented") 14 } 15} 16 17class ViewController: UIViewController{ 18 19 var array = [Int](0...30) 20 21 @IBOutlet weak var collectionView: UICollectionView! 22 23 private let sectionInsets = UIEdgeInsets(top: 20.0, left: 10.0, bottom: 20.0, right: 10.0) 24 private let itemsPerRow: CGFloat = 3 25 26 override func viewDidLoad() { 27 super.viewDidLoad() 28 29 // 選択の条件を設定する 30 //collectionView.allowsSelection = true 31 collectionView.allowsMultipleSelection = true 32 } 33} 34 35extension ViewController: UICollectionViewDataSource { 36 37 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 38 return array.count 39 } 40 41 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 42 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell 43 cell.label.text = String(format: "%02d", indexPath.row) 44 // ここで背景を設定するだけ 45 cell.selectedBackgroundView = CellBgView(num: indexPath.row) 46 return cell 47 } 48 49} 50 51class CustomCell: UICollectionViewCell { 52 53 @IBOutlet weak var label: UILabel! 54 55} 56 57 58// あとはレイアウト用です 59 60extension ViewController: UICollectionViewDelegateFlowLayout { 61 62 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 63 64 let paddingSpace = sectionInsets.left * (itemsPerRow + 1) 65 let availableWidth = UIScreen.main.bounds.width - paddingSpace 66 let withPerItem = availableWidth / itemsPerRow 67 68 //cellの大きさを返す 69 return CGSize(width: withPerItem, height: withPerItem) 70 } 71 72 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { 73 74 return sectionInsets 75 76 } 77 78 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 79 80 return sectionInsets.left 81 82 } 83}

選択されているセルのインデックスパスは、indexPathsForSelectedItemsとかでとれます

投稿2020/05/17 05:40

編集2020/05/17 14:43
退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tsuji71

2020/05/17 14:37

ありがとうございます 上記の方法でうまくいきました また自分でも色々と調べてみて cellForItemAt 内に let selectedBGView = UIView(frame: cell.frame) selectedBGView.backgroundColor = .blue cell.selectedBackgroundView = selectedBGView のような記述をすることでもうまくいきそうです 本当にありがとうございました
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問