現在Realmを使って画像データとテキストを保存し、UICollectionViewで画像のみの表示を行っています。
UICollectionViewのセルをクリックすると画面遷移を行い、保存した画像とテキストを表示させたいと考えています。
イメージとしては、通販サイトなどで商品をクリックし、その詳細ページに飛ぶ感じです。
データの保存とUICollectionViewで画像の表示まではできたのですが、その後画像(セル)をクリックしてデータをどのように遷移先に送るのかがわかりません。
普通の変数などであればSegueで値を渡せると思うのですが、
データベースの場合も表示されている値を格納した変数をSegueで送ることは可能なのでしょうか?
//メンバ変数
var a : ToDo?
var toDoItems:Results<ToDo>?{
do{
let realm = try Realm()
return realm.objects(ToDo)
}catch{
print("エラー")
}
return nil
}
...
extension ViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return toDoItems?.count ?? 0
}
//データを返すメソッド
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
let toDo = toDoItems?[indexPath.row]
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! collectionviewcell
cell.image1.image = toDo?.image
return cell
}
// Cell が選択された場合
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: NSIndexPath) {
var toDo = toDoItems?[indexPath.row]
a = toDo
if a != nil{
performSegueWithIdentifier("toSubViewController",sender: nil)
}
}
// Segue 準備
func prepare(for segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "toSubViewController1") {
let subVC: SubViewController = (segue.destinationViewController as? SubViewController)!
subVC.a1 = a
}
}
}
collectionView(_:cellForItemAt:)
やcollectionView(_:numberOfItemsInSection:)
、collectionView(_:didSelectItemAt:)
)を載せてもらえると具体的なアドバイスができます。toDoItems
という変数はRealmのResults
型の変数ですか?そうだとしたら、コレクションビューのセルを選択したときに呼ばれるメソッド、collectionView(_:didSelectItemAt:)
でセルのindexPath
が取得できるので、ご提示のコードでしているようにlet toDo = toDoItems?[indexPath.row]
などとして該当のデータをtoDoItems
から取り出して次の画面に渡します。Segueにはデータを受け渡すAPIはないので、実際には取得したtoDo
を一旦メンバ変数として保存しておいて、prepare(for segue: UIStoryboardSegue, sender: Any?)
メソッドで次のビューコントローラのメンバ変数としてデータを渡します。