【发布时间】:2019-04-23 18:32:41
【问题描述】:
我在获取值以进行所需组合时遇到问题。我在我的应用程序中使用过滤器屏幕。我问这个问题是为了从问题How to put the of first and last element of Array in Swift 中获取第一个和最后一个元素,它正在工作,但问题出在我的FiterVC 中,首先我选择了选项$400 - $600,然后我选择了$200 - $400。选择后,我在 currentFilter 变量中获取这些值。
private let menus = [
["title": "Price", "isMultiSelection": true, "values": [
["title": "$00.00 - $200.00"],
["title": "$200.00 - $400.00"],
["title": "$400.00 - $600.00"],
["title": "$600.00 - $800.00"],
["title": "$800.00 - $1000.00"],
]],
["title": "Product Rating", "isMultiSelection": true, "values": [
["title": "5"],
["title": "4"],
["title": "3"],
["title": "2"],
["title": "1"]
]],
["title": "Arriving", "isMultiSelection": true, "values": [
["title": "New Arrivials"],
["title": "Coming Soon"]
]]
]
private var currentFilters = [String:Any]()
在didSelect方法中选择值:-
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView === self.menuTableView {
self.currentSelectedMenu = indexPath.row
self.menuTableView.reloadData()
self.valueTableView.reloadData()
}
else {
if let title = self.menus[self.currentSelectedMenu]["title"] as? String, let values = self.menus[self.currentSelectedMenu]["values"] as? [[String:Any]], let obj = values[indexPath.row]["title"] as? String {
if let old = self.selectedFilters[title] as? [String], let isAllowedMulti = self.menus[self.currentSelectedMenu]["isMultiSelection"] as? Bool, !old.isEmpty, !isAllowedMulti {
var temp = old
if old.contains(obj), let index = old.index(of: obj) {
temp.remove(at: index)
}
else {
temp.append(obj)
}
self.selectedFilters[title] = temp
}
else {
self.selectedFilters[title] = [obj]
}
self.valueTableView.reloadData()
}
}
}
然后点击应用按钮:-
@IBAction func applyButtonAction(_ sender: UIButton) {
self.delegate?.didSelectedFilters(self, with: self.selectedFilters)
printD(self.selectedFilters)
self.dismiss(animated: true, completion: nil)
}
当我打印 selectedFilters 时,我得到了这些值:-
currentFilters ["Price": ["$400.00 - $600.00", "$200.00 - $400.00"]]
通过使用这种方法,我可以从字典中获取第一个和最后一个值,如下所示:-
if let obj = currentFilters["Price"] as? [String] {
self.priceRange = obj
printD(self.priceRange)
let first = priceRange.first!.split(separator: "-").first!
let last = priceRange.last!.split(separator: "-").last!
let str = "\(first)-\(last)"
let str2 = str.replacingOccurrences(of: "$", with: "", options: NSString.CompareOptions.literal, range: nil)
newPrice = str2
printD(newPrice)
}
结果是:-
400.00 - 400.00
但我真正想要的是200 - 600。我怎样才能做到这一点。请帮忙?
【问题讨论】:
-
用“-”分割数组后,检查是否选择了正确的数组项。 priceRange.first!.split(separator: "-") 和 priceRange.last!.split(separator: "-") 中有哪些项目?
-
@wings 它不起作用,因为您不是在寻找最大的价值,而是在寻找第一个和最后一个元素。这些方法不知道里面包含的值。
-
为什么不使用映射表,例如
0 = 0-200, 1 = 200-400等?下限值始终为x * 200,上限值始终为x * 200 + 200?这避免了使用split和replaceOccurrences进行烦人的提取 -
为按钮分配标签 (0-5)。将
currentFilters声明为整数 arrayvar currentFilters = [Int]()。选择/取消选择过滤器时,将标签添加/从数组中添加/删除。如前所述,较低的值为tag * 200,较高的值为tag * 200 + 200。 -
你可以。这是设计的问题。我只是提出了一个建议,以改进一个非常繁琐且效率低下的设计。
标签: ios arrays swift dictionary swift4