如何从Eureka的MultivaluedSection中获取选中值?
获取Eureka MultivaluedSection中选中值的正确方法
我明白你在Swift 4.1里使用Eureka框架时遇到的问题——想把MultivaluedSection里用户选中的选项存入数组,但之前的方法行不通。问题出在你用错了获取Section的API,下面是正确的解决办法:
核心问题分析
你之前尝试用self.form.rowBy(tag: "instruments")来获取MultivaluedSection,但rowBy(tag:)是用来查找单个Row的方法,而你的"instruments"是MultivaluedSection的tag,所以这个方法根本找不到对应的Section,自然无法获取值。
正确的实现步骤
1. 一次性获取所有选中值
使用sectionBy(tag:)方法定位你的MultivaluedSection,然后遍历其中的所有Row,提取每个ActionSheetRow的选中值:
// 获取目标MultivaluedSection实例 if let instrumentsSection = self.form.sectionBy(tag: "instruments") as? MultivaluedSection { // 遍历所有行,过滤掉未选中的项(value为nil的情况) let selectedInstruments = instrumentsSection.rows.compactMap { row in (row as? ActionSheetRow<String>)?.value } // 现在selectedInstruments就是所有选中值组成的数组 print(selectedInstruments) // 这里可以把数组存到你需要的变量里 }
2. 实时更新选中值(可选)
如果想要在用户每次选择或修改选项时实时更新你的数组,可以在创建ActionSheetRow时添加onChange回调:
MultivaluedSection(multivaluedOptions: [.Insert, .Delete], header: "Primary Instrument") { $0.tag = "instruments" $0.multivaluedRowToInsertAt = { _ in ActionSheetRow<String> { $0.title = "Tap to Select" $0.options = ["Vocals", "Guitar", "Bass", "Keyboards", "Ukelele"] $0.onChange { [weak self] _ in self?.updateSelectedInstruments() } } } $0 <<< ActionSheetRow<String> { $0.title = "Tap to Select" $0.options = ["Vocals", "Guitar", "Bass", "Keyboards", "Ukelele"] $0.onChange { [weak self] _ in self?.updateSelectedInstruments() } } } // 定义专门更新选中数组的方法 private func updateSelectedInstruments() { if let instrumentsSection = self.form.sectionBy(tag: "instruments") as? MultivaluedSection { let selectedInstruments = instrumentsSection.rows.compactMap { row in (row as? ActionSheetRow<String>)?.value } // 这里将selectedInstruments赋值给你的目标数组 print("实时选中的乐器:", selectedInstruments) } }
这样每次用户修改选项时,你的数组都会自动同步更新。
内容的提问来源于stack exchange,提问作者Larry Seyer
相关产品推荐
相关产品推荐

