如何使用 EurekaForm 库获取选定值并在列表中设置默认值 / Swift

How to get the selected value and set a default value in a list with EurekaForm Library / Swift

我的项目使用 xCode 9Swift 4 和 "Eureka form library"。

情况:

我有一个带有列表和按钮的表单。

我需要帮助解决这些 2 问题 :

  1. 当点击按钮时我想打印选择的值
  2. 我希望能够为列表设置一个元素作为默认选择值

我的 code :

import UIKit
import Eureka

class myPage: FormViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        createForm()
    }


    func createForm(){
        form
        +++ Section("Sample list ")
        form +++ SelectableSection<ListCheckRow<String>>("Continents", selectionType: .singleSelection(enableDeselection: false))

        let continents = ["Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"]

        for element in continents {
            form.last! <<< ListCheckRow<String>(element){ listRow in
                listRow.title = element
                listRow.selectableValue = element
                listRow.value = nil
            }
        }

        form.last! <<< ButtonRow("Button1") {row in
            row.title = "Get List Value"
            row.onCellSelection{[unowned self] ButtonCellOf, row in

            print ("Selected List Value = ????????")
        }
    }
}

提前致谢。

用于打印所有表格值:

print(form.values())

这将打印由行 tag.

键入的所有形式 values 的字典

对于这种情况,它打印如下(选择Australia):

["Asia": nil, "Africa": nil, "Antarctica": nil, "Australia": Optional( "Australia"), "Europe": nil, "South America": nil, "Button1": nil, "North America": nil]

Eureka 的 SelectableSection 也有 selectedRow()(多选 selectedRows())方法。

因此您可以获得这样的选定值:

首先只需将标签添加到 SelectableSection 标签。

form +++ SelectableSection<ListCheckRow<String>>("Continents", selectionType: .singleSelection(enableDeselection: false)) { section in
   section.tag = "SelectableSection"
}

现在选择按钮

form <<< ButtonRow("Button1") { row in 
        .. // button setup
    }.onCellSelection { [unowned self] (cell, row) in
        if let section = self.form.section(by: "SelectableSection") as?
                               SelectableSection<ListCheckRow<String>> {
            print(section.selectedRow()?.value ?? "Nothing is selected") 
        }
    }

现在选择默认值:

let defaultContinent = "Antarctica" 

现在在 Button 的 onCellSelection:

}.onCellSelection { [unowned self] (cell, row) in
    .. // printing the selected row as above
    if let row = self.form.row(by: defaultContinent) as? ListCheckRow<String> {
       row.selectableValue = defaultContinent 
       row.didSelect()
    }
}