LoginSignup
5
5

More than 5 years have passed since last update.

Eurekaのセレクトボックスに後からデータを入れる方法

Posted at

概要

Eurekaというフォーム作成ライブラリを使っている.
APIで取得したデータをEurekaのフォームのセレクトボックスのデータにセットする方法について説明する.
何か間違いがあれば,ご指摘お願い致します.

環境

問題

APIからデータを取得した際,非同期的にデータを取得するため,APIから取得したデータがセレクトボックスに表示されず,初期にセットしたデータが表示されてしまう.

解決法

ViewController.swift
import UIKit
import Eureka

class ViewController: FormViewController {

    var locations: [String] = []
    var activeLocation: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // APIから位置データの取得
        LocationService.getLocations{ responseLocations in
            self.locations = responseLocations      // このままではformには反映されない

            // タグから対象のフォームの情報を取得
            if let LocationsRow = self.form.rowBy(tag: "Locations") {
                // 対象のセレクトボックスにデータを入れるために.cellUpdateを呼ぶ
                LocationsRow.updateCell()
            }
        }

        form
        +++ Section("Source")
            <<< PushRow<String>("Locations"){
                $0.title = "場所"
                $0.selectorTitle = "場所の選択"
                $0.options = self.locations
            }.onChange { row in
                self.activeLocation = row.value ?? self.locations[0]
            }.cellUpdate { cell, row in             // .updateCellで実行される
                row.options = self.locations
            }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

解説

formの部分

form
    +++ Section("Source")
        <<< PushRow<String>("Locations"){
            $0.title = "場所"
            $0.selectorTitle = "場所の選択"
            $0.options = self.locations
        }.onChange { row in
            self.activeLocation = row.value ?? self.locations[0]
        }.cellUpdate { cell, row in             // .updateCellで実行される
            row.options = self.locations
        }

1. .cellUpdateの追加

formに.cellUpdateを追加し,row.options = self.locationsを記述し,後からデータを挿入する記述を行う.
.cellUpdateはこういう用途らしい

Called each time the cell appears on screen. You can change the appearance here using variables that may not be present on cellSetup().

セルが表示されるたびに呼ばれるところらしい.またcellSetup()で与えられていない変数を利用して表示を変更できるらしい.

2. tagの追加
<<< PushRow<String>("ここにタグ"){のように,タグを追加する.
これで外からアクセスするための準備が完了.

外から.cellUpdateの発火

// APIから位置データの取得
LocationService.getLocations{ responseLocations in
    self.locations = responseLocations      // このままではformには反映されない

    // タグから対象のフォームの情報を取得
    if let LocationsRow = self.form.rowBy(tag: "Locations") {
        // 対象のセレクトボックスにデータを入れるために.cellUpdateを呼ぶ
        LocationsRow.updateCell()
    }
}

1. タグから対象のフォームにアクセス
self.form.rowBy("対象のタグ名")で対象のフォームの情報を取得できる.

2. updateCell().cellUpdateの発火
LocationsRow.updateCell().cellUpdateを実行させる.

5
5
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
5
5