[英]Reload tableview based on segments options
我正在嘗試在用戶更改控件段時更改表數據。 但是現在我的代碼崩潰了。 這是我設置細分的方法:
let w = view.frame.width
let s = PinterestSegment(frame: CGRect(x: 20, y: 117, width: w - 40, height: 40), titles: ["Our faviorte", "Restuarnt", "Coffee", "Pharmacy", "Supermarketr", "Home", "Wemoent' Style", "Man's Style", "Beauty", "Travel"])
s.style.titleFont = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 5))
view.addSubview(s)
TableView數據從api保存,並根據細分選項進行過濾。
var info = Shops(shopname: shopName, Logo: logoString, family_id: familiy_id , design : designImage , rate : rate, time : time )
self.shops.append(info)
// filters all the segments this way
self.coffee = self.shops.filter { $0.shopname == "Starbucks" }
現在,當在ViewdidLoad中更改分段時:
s.valueChange = { index in
if index == 1 {
print(self.coffee)// it prints the data correctly
self.shops = self.coffee
}
if index == 2 {
self.shops = self.Restuarnt
}
if index == 3 {
self.shops = self.Pharmacy
}
self.tableView.reloadData()
}
我收到一個fatal error: Index out of range
數據源和委托:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchActive {
return auxiliar!.count
}else{
return allShops.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if searchActive
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
let entry1 = auxiliar?[indexPath.row]
cell.shopImage.hnk_setImage(from: URL(string: (entry1?.Logo)!))
cell.shopName.text = entry1?.shopname
cell.backgroundColor = UIColor(white: 1 , alpha : 0.5)
cell.time.text = entry1?.time
cell.star.rating = Double((entry1?.rate)!)
return cell
}
else {
let shop = allShops[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShopTableViewCell
let entry = shops[indexPath.row]
cell.shopImage.hnk_setImage(from: URL(string: entry.Logo))
cell.shopName.text = entry.shopname
cell.star.rating = Double(entry.rate)
cell.time.text = entry.time
cell.backgroundColor = UIColor(white: 1 , alpha : 0.5)
return cell
}
}
檢查UITableView的委托和數據源: numberOfRowsInSection
和cellForRowAtIndexPath
。 您的數據源( self.Restuarnt
, self.Pharmacy
)中有tableView的單元self.Restuarnt
引的數據。
首先登錄控制台找到崩潰點,它可能是通過tableview數據源方法崩潰的。 確保self.Restuarnt和self.Pharmacy可以正確打印數據。 還有一件事是,您使用了多個If語句 ! 而是使用if-else-if Ladder ,因為一旦索引匹配,就沒有必要檢查其他索引! !
這種方法應該是這樣的,
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchActive {
return auxiliar!.count
}else{
return self.shops.count
}
}
因為每次您在細分上設置self.shops都會改變
您可以將選定的段索引保存在為類全局定義的某個變量中,並在cellForRow索引方法中訪問該變量
而且我認為您可以對此行發表評論,因為您在cellForRow索引方法中未使用任何位置
讓商店= allShops [indexPath.row]
您可能在行數上犯了一個錯誤。 每當細分發生變化時,您都需要重新聲明tableview。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.