LoginSignup
1
2

More than 3 years have passed since last update.

[Swift] 遷移先で変更した配列を遷移元に反映させ、Label等に表示させる方法

Posted at

はじめに

今回はNavigationControllerを用いて、画面遷移を行っています。そのため、遷移先から遷移元に戻る時に呼ばれるnavigationControllerのwillShowを使っています。また、collectionViewのCell内にLabelを置き、そこに配列(String)の値を表示させています。

開発環境

macOS 11.0.1
Xcode version 12.2
Swift version 5.3.1

コード

親画面にはString型で変数aを与え、初期値として5個の何の値も入っていない値を与えておきます。これを、collectionViewを用いて、Cell内に設置したLabelに先程の値を与えています。遷移先で変更された配列を遷移元に渡した時にプロパティ・オブザーバを設定してあげることで変更が起こった時の処理を書くことができるようになります。オブザーバは、プロパティ変更前に呼ばれる willSet と、変更後に呼ばれる didSet があります。今回は、変更後に呼ばれるdidsetを使います。

FirstViewContoroller
import UIKit

class ViewController:
                  //collectionViewを用いるため、下の2つを書いておく
UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
   //上と同じ理由で書いておく
    @IBOutlet weak var collectionView: UICollectionView!

    var a = ["","","","",""] {didSet{

       //didset内に書くことで、変数aに変更が起こった場合にreloadDataし、label内の表示           される値も変更することができる
        collectionView.reloadData()

        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()        

    } 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return a.count

    }     

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for:indexPath)
        cell.backgroundColor = .lightGray

        //タグつけしたlabelに変数aの値を順に表示
        var aLabel = cell.contentView.viewWithTag(1) as! UILabel
        aLabel.text = a[indexPath.row]

        return cell
    }

//ほかには、何かしらの方法で遷移するコード書く

}

NextViewController
import UIKit


class NextViewController: UIViewController,UINavigationControllerDelegate {

    @IBOutlet weak var textFiled: UITextField! 

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    //ナビゲーションバーの戻るボタンを押した時に呼ばれる処理。下記を書くことで遷移先で遷移元の値   をいじることができる
     func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {

                                              //親画面のファイル名を記入
        if let controller = viewController as? FirstViewContoroller{

       //今回は変数aの1番目の値を変更する
       //遷移先画面のテキストフィールドに打たれた文字が遷移元の変数aの1番目の値を変更する
            controller.a[0] = textfiled.text!
        }

まとめ

今回のコードで重要なことは、プロパティ・オブザーバの一つであるdidsetです。この中でcollectionView.reloadData()を書くことで、変数である配列に変更が起きた場合に、
collectionView.reloadData()が呼ばれ、cell内のlabelに表示される値を変更毎に更新することができます。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2