根据应用的过滤器过滤UITableView的内容

时间:2017-02-14 15:27:42

标签: ios arrays swift uitableview filter

我试图通过某些过滤器过滤UITableView:

  • 国家/地区
  • 价格范围

以下是我的TVC在过滤之前的样子

TVC ScreenShot

用户可以按区域"美洲"并且只获得

Filtered TVC

这是我按区域过滤的代码

func useFilter() {
    countries.forEach({ (country) in

        let countryRegion = countryToRegionDic[country]

        if (countryRegion != nil && filters.contains(countryRegion!)){

            self.newCountries.append(country)
            self.countries = newCountries.removeDuplicates()
            self.tableView.reloadData()
        }
    })
}

搜索地区词典 -

let countryToRegionDic = [    
"United States" : "America",
"Canada" : "America"]

在这种情况下的问题我正在排序国家,但你可以看到"古巴"得到了新的价格 - 在过滤之前它是275,在-1之后(就像tableView中的最后一个元素)

第二种情况它按价格范围过滤,这是我如何做的

func filterByPrice() {
    prices = prices.filter({$0 >= (100) && $0 <= 200})
    tableView.reloadData()
}

如果我使用过滤器按价格我的应用程序崩溃导致方法 tableView(_ tableView:UITableView,numberOfRowsInSection section:Int) - &gt; INT

我正在返回countriesArray.count

1 个答案:

答案 0 :(得分:0)

Some magic here:

var bound = [ShowData]()
var newBound = [ShowData]()

func useFilter() {
    bound.forEach({ 
        let countryRegion = countryToRegionDic[$0.place]
        if let countryRegion = countryRegion, filters.contains(countryRegion) {

            let a = $0.place
            let b = $0.price

            let lol = ShowData(place: a, price: b)
            newBound.append(lol)
            bound = newBound
        }
    })
    tableView.reloadData()
}