初心者です。
###前提・実現したいこと
swift2でアプリを作っています。
CollectionViewCellを定義してCollectionViewからregisterClassを行い、セルを複数並べました。
並んでいるセルの順番をアプリ起動中に変更できる機能を実装したのですが、ビルドし直すと変更する前の順番に戻ってしまいます。
そこでNSUserDefaultsを使って変更後のセルの順番を保持する機能を追加しようと考えています。
コードを自分なりに書いてみたのですが、エラーなどは出ず、ビルドも成功するものの、コードを書く前と変化はなく、やはりビルドし直すと変更する前の順番に戻ってしまいます。
NSUserDefaultsではこういった画面内の要素の位置などのデータは保存できないのでしょうか。
coreDataやSQLite等を利用しないと実装は難しいのでしょうか。
どなたかご教示お願い致します。
###該当のソースコード
swift
1 struct UserDefaultsKey { 2 static let Cell = "cell" 3 } 4 5 struct SerializedKey { 6 static let cell1 = "Cell1" 7 static let cell2 = "Cell2" 8 static let cell3 = "Cell3" 9 } 10 11 class Cell: NSObject, NSCoding { 12 13 var Cell1: UICollectionViewCell 14 var Cell2: UICollectionViewCell 15 var Cell3: UICollectionViewCell 16 17 init(Cell1: UICollectionViewCell, Cell2: UICollectionViewCell, Cell3: UICollectionViewCell) { 18 self.Cell1 = Cell1 19 self.Cell2 = Cell2 20 self.Cell3 = Cell3 21 } 22 23 required init?(coder aDecoder: NSCoder) { 24 25 self.Cell1 = (aDecoder.decodeObjectForKey(SerializedKey.cell1) as? UICollectionViewCell)! 26 self.Cell2 = (aDecoder.decodeObjectForKey(SerializedKey.cell2) as? UICollectionViewCell)! 27 self.Cell3 = (aDecoder.decodeObjectForKey(SerializedKey.cell3) as? UICollectionViewCell)! 28 } 29 30 func encodeWithCoder(aCoder: NSCoder) { 31 aCoder.encodeObject(self.Cell1, forKey: SerializedKey.cell1) 32 aCoder.encodeObject(self.Cell2, forKey: SerializedKey.cell2) 33 aCoder.encodeObject(self.Cell3, forKey: SerializedKey.cell3) 34 } 35 36 } 37 38 class CustomLayout { 39 40 static let sharedInstance = CustomLayout() 41 42 private let userDefaults = NSUserDefaults.standardUserDefaults() 43 44 func register(Cell1: UICollectionViewCell, Cell2: UICollectionViewCell, Cell3: UICollectionViewCell) { 45 46 let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(Cell(Cell1: Cell1, Cell2: Cell2, Cell3: Cell3)) 47 self.userDefaults.setObject(archivedObject, forKey: UserDefaultsKey.Cell) 48 self.userDefaults.synchronize() 49 } 50 51 var registeredCell: Cell? { 52 53 guard let unarchivedObject = self.userDefaults.objectForKey(UserDefaultsKey.Cell) as? NSData, 54 let cell = NSKeyedUnarchiver.unarchiveObjectWithData(unarchivedObject) as? Cell else { 55 56 57 return nil 58 } 59 60 return cell 61 } 62 } 63
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2016/08/31 08:37