I use xCode 9, swift 4 and "Eureka form library" for my project.
The situation
I have a list of cars with name and unique ID associated this way: 0 - ANY, 1 - VW, 7 - AUDI, 20 - MAZDA
var name_cars: [String] = ["ANY","VW","AUDI","MAZDA"]
var id_cars:[Int] = [0, 1, 7, 20]
I also have a form with "PushRow" and "ButtonRow". On click to the button I want to print the selected car name and ID. I was able to print the car's name but not the ID.
import UIKit
import Eureka
class myPage: FormViewController {
var cars: [String] = ["ANY","VW","AUDI","MAZDA"]
var id_cars:[Int] = [0, 1,7,20]
var selected_car: String = "ANY" //default car
var selected_car_id: Int = 0 //default id car
override func viewDidLoad() {
super.viewDidLoad()
create_form()
}
func create_form(){
form
+++ Section("List")
//list
<<< PushRow<String>() {
$0.title = "Cars"
$0.options = cars
$0.value = "ANY"
$0.tag = "list_element"
$0.selectorTitle = "Choose car"
$0.onChange { [unowned self] row in
self.selected_car = row.value!
self.selected_car_id = ??? // **what should it be here in order to get the ID**
}
}
//button
<<< ButtonRow("Button1") {row in
row.title = "Get Value on Console"
row.onCellSelection{[unowned self] ButtonCellOf, row in
print ("Car selected = ",self.selected_car, " and Id_Car_Selected = ",self.selected_car_id)
}
}
}
}
First of all please conform to the naming convention that class names start with a capital letter and variable names are lowerCamelCased rather than snake_cased.
Swift is an object oriented language. Rather than two separate arrays use a custom struct Car
.
import UIKit
import Eureka
struct Car : Equatable {
let name : String
let id : Int
}
The push row is declared as PushRow<Car>()
and the property displayValueFor
is populated with the name
class MyPage: FormViewController {
let cars = [Car(name: "ANY", id: 0), Car(name: "VW", id: 1), Car(name: "AUDI", id: 7), Car(name: "MAZDA", id: 20)]
var selectedCar : Car!
override func viewDidLoad() {
super.viewDidLoad()
selectedCar = cars[0]
createForm()
}
func createForm() {
form
+++ Section("List")
//list
<<< PushRow<Car>() {
$0.title = "Cars"
$0.options = cars
$0.value = selectedCar
$0.displayValueFor = {
guard let car = $0 else { return nil }
return car.name
}
$0.tag = "list_element"
$0.selectorTitle = "Choose car"
$0.onChange { [unowned self] row in
self.selectedCar = row.value!
}
}
//button
<<< ButtonRow("Button1") {row in
row.title = "Get Value on Console"
row.onCellSelection{[unowned self] ButtonCellOf, row in
print ("Car selected = ", self.selectedCar.name, " and Id_Car_Selected = ", self.selectedCar.id)
}
}
}
}