概要
Eurekaというフォーム作成ライブラリを使っている.
APIで取得したデータをEurekaのフォームのセレクトボックスのデータにセットする方法について説明する.
何か間違いがあれば,ご指摘お願い致します.
環境
- 言語
- Swift3
- 使用ライブラリ
問題
APIからデータを取得した際,非同期的にデータを取得するため,APIから取得したデータがセレクトボックスに表示されず,初期にセットしたデータが表示されてしまう.
解決法
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
を実行させる.