Tableview类别细化

时间:2017-10-04 13:45:07

标签: swift uitableview firebase-realtime-database

我在firebase中有大量数据,我正在tableview上显示。这些数据是附近的不同业务,我想添加一个功能来按业务类型(食品,旅行,购物等)过滤/排序数据。我添加了一个带有分段控件的标签栏,作为过滤/排序功能。当用户选择购物时,我只希望显示购物业务以及要删除的所有其他业务。我尝试了几种不同的方法来做到这一点,但没有成功。我可以在应用程序首次加载时正确填充tableview单元格,但是当选择过滤器/排序选项时,我无法正确加载单元格。这是我目前的代码。

@IBOutlet weak var selects: UISegmentedControl!
@IBAction func selections(_ sender: Any) {
    if selects.selectedSegmentIndex == 0 {
        //all
        print("all")
        cate = 0
        loadposts()
    }
    else if selects.selectedSegmentIndex == 1 {
        //shopping
        print("shopping")
        cate = 1
        loadposts()
    }
    else if selects.selectedSegmentIndex == 2 {
        //food
        print("food")
        cate = 2
        loadposts()
    }
    else if selects.selectedSegmentIndex == 3 {
        //travel
        print("travel")
        cate = 3
        loadposts()
    }
    else if selects.selectedSegmentIndex == 4 {
        //events
        print("event")
        cate = 4
        loadposts()
    }
    else {
        //more
        print("more")
        cate = 5
        loadposts()
    }
}

func loadposts() {
    ref = Database.database().reference()
    let trace = Performance.startTrace(name: "test trace")
    trace?.incrementCounter(named:"retry")
    let userID = Auth.auth().currentUser?.uid
    print(userID!)


   ref.child("Users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let one1 = value?["Coupon Book"] as? String ?? ""
        let two2 = value?["charitylogo"] as? String ?? ""
        print("one1: \(one1)")
        bogus.set(one1, forKey: "bogus")
    let url = URL(string: two2)
    print("Url: \(url!)")
    URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
        if error != nil{
            print(error)
            return
        }
        DispatchQueue.main.async {
           /// self.centernavlogo = UIButton(type: .custom)
            let pim = UIImage(data: data!)
            self.vood.background = pim
            ///self.centernavlogo.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
           /// self.centernavlogo.imageView?.contentMode = .scaleAspectFit
           /// self.centernavlogo.setImage(pim, for: .normal)
          ///  self.centernavlogo.setBackgroundImage(pim, for: .normal)

            /// self.centernavlogo.tintColor = UIColor.white

            ///self.centernavlogo.setBackgroundImage(pim, for: .normal)


        }

    }).resume()

    Database.database().reference().child("Coupons").child(one1).observe(.childAdded) { (Snapshot : DataSnapshot) in
        if let dict = Snapshot.value as? [String: Any] {
            let captiontext = dict["company name"] as! String
            let offerx = dict["totaloffer"] as! String
            let logocomp = dict["logo"] as! String
            let actchild = dict["childx"] as! String
            let categ = dict["category"] as! String
            let post = Post(captiontext: captiontext, PhotUrlString: actchild, offertext: offerx, actualphoto: logocomp, cat2: categ)
            self.posts.append(post)
            self.tableview.reloadData()

            print(self.posts)
        }
    }
    }) { (error) in
        print(error.localizedDescription)
    }
    trace?.stop()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.

}
func delay(_ delay:Double, closure:@escaping ()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

}
extension ViewController : UITableViewDataSource {


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableview.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! prot

    if cate == 0{
        ///home
        if posts[indexPath.row].cat1 == "" {

        }else{

        }
    }else
    if cate == 1{
    ///shopping
    if posts[indexPath.row].cat1 == "shopping" {

    }
}else
    if cate == 2{
    ///food
    if posts[indexPath.row].cat1 == "food" {

    }
}else
    if cate == 3{
    ///travel
    if posts[indexPath.row].cat1 == "travel" {

    }
}else
    if cate == 4{
    ///event
    if posts[indexPath.row].cat1 == "event" {

    }
}else
    if cate == 5{
    ///more
    if posts[indexPath.row].cat1 == "more" {
            posts.remove(at: indexPath.item)

        DispatchQueue.main.async {
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
        }
           print("category 5 running")
        }
        tableView.reloadData()
    }
    if cate == 6{
        ///gps
    }

    cell.cllimg?.image = nil
    cell.maintxt.text = nil
    cell.sidetxt.text = nil
    cell.maintxt.text = posts[indexPath.row].caption
    cell.sidetxt.text = "Offers: \(posts[indexPath.row].offercount)"



    let hone = posts[indexPath.row]
    if let maria = hone.actphot {
        let url = URL(string: maria)
        URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
            if error != nil{
                print(error)
                return
            }
            cell.cllimg?.contentMode = .scaleAspectFit
            DispatchQueue.main.async {

            cell.cllimg?.image = UIImage(data: data!)
            }

        }).resume()
    }

    return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    passinfo.set("\(posts[indexPath.row].photourl)", forKey: "passinfo")
    self.performSegue(withIdentifier: "yourSegue", sender: self)
}



}

使用上面的代码,当选择类别时,表格为空白

if cate == 5{
    ///more
    if posts[indexPath.row].cat1 == "more" {
        tableView.beginUpdates()
            posts.remove(at: indexPath.item)
            tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
           print("category 5 running")
        }
        tableView.endUpdates()
    }

使用上面的代码,应用程序崩溃并给我这个错误。

  

由于未捕获的异常终止应用程序' NSInternalInconsistencyException',原因:'无效更新:第0部分中的行数无效。更新后现有部分中包含的行数(14)必须等于更新前的该部分中包含的行数(15),加上或减去从该部分插入或删除的行数(0插入,0删除)和加或减移入的行数或超出该部分(0移入,0移出)。'

我还尝试删除posts.remove(at: indexPath.item)tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none),但都没有效果。

1 个答案:

答案 0 :(得分:0)

尝试在tableView.beginUpdates()

之前移动此行
posts.remove(at: indexPath.item)
  

更新后现有部分中包含的行数   (14)必须等于该部分中包含的行数   在更新(15)之前,加上或减去插入的行数或   从该部分删除(0插入,0删除)和加号或减号   移入或移出该部分的行数(0移入,0   搬出去了。

因为错误表明更新之前的posts数组计数在更新之后也必须相等。

posts.remove(at: indexPath.item)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
tableView.endUpdates()