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

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

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

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

Q&A

0回答

1042閲覧

【Swift】collectionViewのセルの表示数をコントロールしたい

konakizzi_mk

総合スコア21

Swift

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

0グッド

0クリップ

投稿2021/04/18 10:40

編集2021/04/18 10:41

##実現したいこと
Collectionviewを使って、スマホの画像を表示させたり削除させたりできるような機能を作っています。(Twitterやinstagramの投稿画面に似たようなもの)
そこで表示できる画像の制限が4枚とした場合、1枚削除したとしたら、もう1枚だけ表示できる
といったことを実現させたいのですが、今の実装だと1枚削除後、追加で複数枚選択できるようになってしまっています。
collectionviewのデータの処理が理解し切れていないため、どうやったら再現できるかご教示いただきたいです。

viewController↓

swift

1import UIKit 2import DKImagePickerController 3 4class PictureViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate { 5 6 var images: [UIImage] = [] 7 var maxSelect = 4 8 9 @IBOutlet weak var collectionView: UICollectionView! 10 11 12 override func viewDidLoad() { 13 super.viewDidLoad() 14 // XIBの呼び出し 15 self.loadNib() 16 setup() 17 addLongTapGesture() 18 19 } 20 @IBAction func tapButton(_ sender: Any) { 21 let pickerController = DKImagePickerController() 22 pickerController.maxSelectableCount = maxSelect 23 pickerController.didSelectAssets = { [unowned self] (assets: [DKAsset]) in 24 for asset in assets { 25 if asset.type == .photo { 26 asset.fetchFullScreenImage(completeBlock: { image, info in 27 guard let image = image else { 28 return 29 } 30 images.append(image) 31 self.collectionView.reloadData() 32 }) 33 } 34 } 35 } 36 present(pickerController, animated: true, completion: nil) 37 } 38 39 // 画面で呼び出すXIBの設定 40 private func loadNib() { 41 let nib = UINib(nibName: "PictureCell", bundle: nil) 42 collectionView.register(nib, forCellWithReuseIdentifier: "PictureCell") 43 } 44 //セルのレイアウト 45 private func setup(){ 46 let layout = UICollectionViewFlowLayout() 47 //セクションの上下左右の位置(一旦仮) 48 layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5) 49 collectionView.collectionViewLayout = layout 50 //Cellの幅と高さサイズ(一旦仮) 51 layout.itemSize = CGSize(width: 220, height: 220) 52 collectionView.alwaysBounceHorizontal = true 53 } 54 55 func addLongTapGesture() { 56 let longTapGesture = UILongPressGestureRecognizer(target:self,action:#selector(longTap(gesture:))) 57 collectionView.addGestureRecognizer(longTapGesture) 58 } 59 60 @objc func longTap(gesture:UILongPressGestureRecognizer){ 61 print("ロングタップ成功") 62 switch gesture.state{ 63 //ロングタップの開始時 64 case.began: 65 guard 66 let selectedIndexPath = collectionView.indexPathForItem(at:gesture.location(in:collectionView))else{ 67 break 68 } 69 collectionView.beginInteractiveMovementForItem(at:selectedIndexPath) 70 //セルの移動中 71 case.changed: 72 collectionView.updateInteractiveMovementTargetPosition(gesture.location(in:gesture.view)) 73 //セルの移動完了時 74 case.ended: 75 collectionView.endInteractiveMovement() 76 default: 77 collectionView.cancelInteractiveMovement() 78 } 79 } 80 81 82 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 83 return images.count 84 } 85 86 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 87 88 var cell: UICollectionViewCell? 89 var imageView: UIImageView? 90 91 cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PictureCell", for: indexPath)as! PictureCell 92 93 cell.imageView.image = images[indexPath.row] 94 cell.index = indexPath 95 cell.delegate = self 96 return cell! 97 } 98 99 //セルの並び替えを可とする 100 func collectionView(_ collectionView:UICollectionView, canMoveItemAt indexPath:IndexPath)-> Bool { 101 return true 102 } 103 //移動したときの挙動 104 func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { 105 reorderCells(sourceIndex: sourceIndexPath.item, destinationIndex: destinationIndexPath.item) 106 } 107 108 // MARK: - PRIVATE METHODS 109 110 /// セルの移動 111 /// 112 /// - Parameters: 113 /// - sourceIndex: 移動元の位置 114 /// - destinationIndex: 移動先の位置 115 private func reorderCells(sourceIndex: Int, destinationIndex: Int) { 116 //画像の入れ替え 117 let image = images.remove(at: sourceIndex) 118 images.insert(image, at: destinationIndex) 119 } 120} 121extension PictureViewController: deletdelegate { 122 func deletDate(index: Int) { 123 images.remove(at: index) 124 collectionView.reloadData() 125 126 } 127}

カスタムセル↓

Swift

1import UIKit 2 3protocol deletdelegate { 4 func deletDate(index: Int) 5} 6 7class PictureCell: UICollectionViewCell { 8 9 @IBOutlet var imageView: UIImageView! 10 @IBOutlet var tapRemovebtn: UIButton! 11 12 override func awakeFromNib() { 13 super.awakeFromNib() 14 // Initialization code 15 } 16 17 var delegate: deletdelegate? 18 var index: IndexPath? 19 20 @IBAction func removeBtnAction(_ sender: Any) { 21 print("タップ") 22 delegate?.deletDate(index: (index?.row)!) 23 } 24 25}

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

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

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

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

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

hoshi-takanori

2021/04/18 14:22

pickerController.maxSelectableCount = maxSelect - images.count とすれば良いのでは。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問