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

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

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

Swift 2は、Apple社が独自に開発を行っている言語「Swift」のアップグレード版です。iOSやOS X、さらにLinuxにも対応可能です。また、throws-catchベースのエラーハンドリングが追加されています。

Q&A

解決済

1回答

2627閲覧

UICollectionViewCellの並び替えを保存したい

退会済みユーザー

退会済みユーザー

総合スコア0

Swift 2

Swift 2は、Apple社が独自に開発を行っている言語「Swift」のアップグレード版です。iOSやOS X、さらにLinuxにも対応可能です。また、throws-catchベースのエラーハンドリングが追加されています。

0グッド

0クリップ

投稿2016/09/02 07:14

編集2016/09/05 06:31

CollectionViewのcellの並べ替えを保存したいです。

並べ替えられる機能は実装できたのですが、並べ替えが保存されずビルドし直すと、並べ替え前の順番に戻ってしまっています。
並び順を保持する方法は何かありませんか?
ご教示よろしくお願いします。

swift

1import UIKit 2 3class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { 4 5 var collectionView: UICollectionView? 6 var longPressGesture: UILongPressGestureRecognizer? 7 var selectedIndexPath: NSIndexPath? 8 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 self.setupSubviews() 12 self.autolayoutSubviews() 13 14 self.navigationItem.rightBarButtonItem = self.editButtonItem() 15 } 16 17 func setupSubviews() { 18 19 let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() 20 flowLayout.minimumInteritemSpacing = 10.0 21 flowLayout.minimumLineSpacing = 10.0 22 flowLayout.sectionInset = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) 23 flowLayout.itemSize = CGSizeMake(300.0, 100.0) 24 25 self.collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout) 26 self.collectionView!.translatesAutoresizingMaskIntoConstraints = false 27 self.collectionView!.dataSource = self 28 self.collectionView!.delegate = self 29 30 self.collectionView!.registerClass(FirstCell.self, forCellWithReuseIdentifier: "FirstCell") 31 self.collectionView!.registerClass(SecondCell.self, forCellWithReuseIdentifier: "SecondCell") 32 self.collectionView!.registerClass(ThirdCell.self, forCellWithReuseIdentifier: "ThirdCell") 33 34 self.collectionView!.backgroundColor = UIColor.whiteColor() 35 self.view.addSubview(self.collectionView!) 36 37 longPressGesture = UILongPressGestureRecognizer(target: self, action: 38 #selector(ViewController.handleLongGesture(_:))) 39 40 41 longPressGesture?.minimumPressDuration = 0.5 42 43 self.longPressGesture!.enabled = false 44 45 46 self.collectionView?.addGestureRecognizer(self.longPressGesture!) 47 } 48 49 func autolayoutSubviews() { 50 51 self.collectionView!.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true 52 self.collectionView!.leadingAnchor.constraintEqualToAnchor(self.view.leadingAnchor).active = true 53 self.collectionView!.trailingAnchor.constraintEqualToAnchor(self.view.trailingAnchor).active = true 54 self.collectionView!.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor).active = true 55 } 56 57 58 override func setEditing(editing: Bool, animated: Bool) { 59 super.setEditing(editing, animated: animated) 60 61 self.collectionView!.allowsMultipleSelection = editing 62 let indexPaths: [NSIndexPath] = self.collectionView!.indexPathsForVisibleItems() 63 64 for indexPath in indexPaths { 65 self.collectionView!.deselectItemAtIndexPath(indexPath, animated: false) 66 let cell: UICollectionViewCell = self.collectionView!.cellForItemAtIndexPath(indexPath)! 67 68 } 69 70 if editing { 71 self.longPressGesture!.enabled = true 72 } 73 else { 74 self.longPressGesture!.enabled = false 75 } 76 77 } 78 79 80 81 func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 82 return 3 83 } 84 85 86 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 87 let cellTypeNumber = indexPath.item % 3 88 switch cellTypeNumber { 89 case 0: 90 let cell1 = collectionView.dequeueReusableCellWithReuseIdentifier("FirstCell", forIndexPath: indexPath) as! FirstCell 91 cell1.backgroundColor = UIColor.redColor() 92 return cell1 93 94 case 1: 95 let cell2 = collectionView.dequeueReusableCellWithReuseIdentifier("SecondCell", forIndexPath: indexPath) as! SecondCell 96 cell2.backgroundColor = UIColor.yellowColor() 97 return cell2 98 99 default: 100 let cell3 = collectionView.dequeueReusableCellWithReuseIdentifier("ThirdCell", forIndexPath: indexPath) as! ThirdCell 101 cell3.backgroundColor = UIColor.greenColor() 102 return cell3 103 } 104 } 105 106 func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { 107 } 108 109 110 func handleLongGesture(gesture: UILongPressGestureRecognizer) { 111 112 switch(gesture.state) { 113 case UIGestureRecognizerState.Began: 114 guard let selectedIndexPath = collectionView?.indexPathForItemAtPoint(gesture.locationInView(collectionView!)) else { 115 break 116 } 117 collectionView?.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath) 118 case UIGestureRecognizerState.Changed: 119 collectionView?.updateInteractiveMovementTargetPosition(gesture.locationInView(gesture.view!)) 120 case UIGestureRecognizerState.Ended: 121 collectionView?.endInteractiveMovement() 122 default: 123 collectionView?.cancelInteractiveMovement() 124 } 125 126 127 128 } 129 130 131 132} 133

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

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

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

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

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

guest

回答1

0

ベストアンサー

前回の質問を見たところ、NSUserDefaultsにセルを保存すればいいと理解したのだと思いますが、セルを保存するんじゃありません。セルの「並び順」を保存するんです。

通常、セルは配列に入っているデータを表示しますから、その場合は配列データを保存すればいいということになります。しかし、前回の質問のコードを見る限り、配列のデータを表示しているのではないような気もしますので、どのようにしてセルを表示しているのか(cellForItemAtIndexPath等)と、どのようにしてセルを並べ替えしているかの具体的なコードを見せてもらったらアドバイスができると思います。


(9/5 21:05回答追記)

ソースコードを参照したところ、並び順を定義しているデータがどこにもないので、まずは並び順を定義するデータから作る必要があります。じゃないと並び順を保存できません。結局のところそれはどのセルIDを何番目に表示するかという定義ですから、セルIDの配列を作るのが一番やりやすいです。

具体的なサンプルを示します。
(1)ViewControllerのプロパティに以下を追加

swift

1var cellIDs:[String] = ["FirstCell","SecondCell","ThirdCell"]

(2)viewDidLoad()内に以下の読み込み処理を追加

swift

1if let cellIDs = NSUserDefaults.standardUserDefaults().arrayForKey("cellIDs") { 2 // 並び順が保存されていれば、それを読み込み 3 self.cellIDs = cellIDs as! [String] 4}

(3)cellForItemAtIndexPath内のswitch文を以下のようにindexPath位置のセルIDによって表示セルを切り分けるよう修正

swift

1switch cellIDs[indexPath.item] { 2case "FirstCell": 34case "SecondCell": 56default: 78}

(4)moveItemAtIndexPath内に以下の配列並べ替え処理と保存処理を追加

swift

1// 移動元をカット 2let movingItem = cellIDs.removeAtIndex(sourceIndexPath.item) 3// 移動先に挿入 4cellIDs.insert(movingItem, atIndex: destinationIndexPath.item) 5// 並び順を保存 6NSUserDefaults.standardUserDefaults().setObject(cellIDs, forKey: "cellIDs")

投稿2016/09/05 05:53

編集2016/09/05 12:44
TakeOne

総合スコア6299

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

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

退会済みユーザー

退会済みユーザー

2016/09/05 06:36

ご回答有り難うございます。 質問を編集し、コードを追加しますね。 そうなるとSourceIndexPathを保存するのでしょうか。 保存するデータ型はString型になりますか? ご教示よろしくお願いいたします。
TakeOne

2016/09/05 12:36

ソースコードを見せてもらったので、回答を追記しました。
退会済みユーザー

退会済みユーザー

2016/09/06 01:41

保存できました。 どのセルIDを何番目に表示するかという定義をする、勉強になりました。 感謝いたします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問