現在SwiftでUICollectionViewを使ったアプリを開発しています。
セルを格子状に配置しており、なぞられたセルの背景色をリアルタイムで変更したいのですが方法が分かりません。
touchesBeganメソッドでなぞられた座標をリアルタイムで取得することはできています。
解決策をご教授いただければ幸いです。
Swift
1import UIKit 2 3class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { 4 @IBOutlet weak var myCollectionView: UICollectionView! 5 6 override func viewDidLoad() { 7 super.viewDidLoad() 8 let flowLayout = UICollectionViewFlowLayout() 9 let margin: CGFloat = 0.2 10 flowLayout.itemSize = CGSize(width: 10.0, height: 10.0) 11 flowLayout.minimumInteritemSpacing = margin 12 flowLayout.minimumLineSpacing = margin 13 flowLayout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin) 14 myCollectionView.collectionViewLayout = flowLayout 15 myCollectionView.allowsMultipleSelection = true 16 17 } 18 19 // cellの数 20 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 21 return 100 22 } 23 24 // cellの情報 25 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 26 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) 27 cell.backgroundColor = UIColor.white 28 29 return cell 30 } 31 32 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 33 let cell = collectionView.cellForItem(at: indexPath) 34 cell?.backgroundColor = UIColor.green 35 } 36 37 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 38 print("touchesMoved") 39 } 40} 41 42extension UICollectionView { 43 override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 44 self.next?.touchesBegan(touches, with: event) 45 } 46 47 override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 48 self.next?.touchesMoved(touches, with: event) 49 // タッチイベントを取得 50 let touchEvent = touches.first! 51 52 // ドラッグ後の座標 53 let newDx = touchEvent.location(in: self).x 54 let newDy = touchEvent.location(in: self).y 55 print(newDx, newDy) 56 } 57}
回答2件
あなたの回答
tips
プレビュー