我在项目中使用xCode 9,swift 4和“ Eureka表单库”。
情况
我有一个具有以下名称和唯一ID的汽车列表:0-任何,1-大众,7-奥迪,20-马自达
var name_cars: [String] = ["ANY","VW","AUDI","MAZDA"]
var id_cars:[Int] = [0, 1, 7, 20]
我也有一个带有“ PushRow”和“ ButtonRow”的表格。 在单击按钮时,我要打印所选的汽车名称和ID。 我可以打印汽车的名称,但不能打印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)
}
}
}
}
答案 0 :(得分:1)
首先,请遵循命名约定,即类名以大写字母开头,变量名称为 lowerCamelCased 而不是 snake_cased 。
Swift是一种面向对象的语言。而不是两个单独的数组使用自定义结构Car
。
import UIKit
import Eureka
struct Car : Equatable {
let name : String
let id : Int
}
将推行声明为PushRow<Car>()
,并在属性displayValueFor
中填充名称
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)
}
}
}
}