第一次获取重复的tableview单元格 [英] Getting duplicate tableview cells after first time

查看:55
本文介绍了第一次获取重复的tableview单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,有一个添加按钮,单击时将添加一个新的tableviewcell.但是,问题是我第一次获得重复的单元格.本质上,当我第二次单击时,我得到了2个重复项,第三次单击时是3,依此类推....请查看屏幕快照中的图像:

In my app, there is an add button, when clicked will add a new tableviewcell. However the problem is I am getting duplicate cells after the first time. Essentially, I am getting 2 duplicates when I click second time, 3 on third and so on.... Please see the images for the screenshot:

上面的图像是第一个屏幕.单击"+"将添加一个新单元格,如下图所示:

The above image is the first screen. Clicking '+' will add a new cell, which looks like the below images:

现在保存后,

现在,如果我离开该视图并返回,再次单击添加并创建一个新的单元格,它将为我提供以上段落中提到的重复项(即,第二次为2,第三次为3,依此类推) ...). 这是屏幕截图:

Now if I go out of this view and come back, click add again and create a new cell, it gives me duplicates as mentioned in the above paragraphs (that is, 2 for second time, 3 for third time and so on...). Here is the screenshot:

这是我正在使用的代码:

Here is the code I am using:

 @IBAction func addBasket(_ sender: UIButton) {

    let prefs         = UserDefaults.standard
    let status        = prefs.string(forKey: "status")

    if(status != nil){

        if( status == "pending"){

            if(BasketItemList.count < 5 ) {

                self.addpost()

            } else {


                let alert = SCLAlertView()
                alert.showWarning("Basket", subTitle: "Upgrade to add more")

            }



        } else {

            if(BasketItemList.count < 50 ) {

                self.addpost()

            } else {

                let alert = SCLAlertView()
                alert.showWarning("Basket", subTitle: "Upgrade to add more")

            }



        }


    }



}


func addpost() {

    let appearance = SCLAlertView.SCLAppearance(
        showCloseButton: false
    )

    let alert = SCLAlertView(appearance : appearance)
    let txt = alert.addTextField("Enter name")
    alert.addButton("Save") {

        if txt.text?.characters.count != 0 {

            let basketname : String = txt.text!

            let userID = FIRAuth.auth()?.currentUser?.uid

            let postitem : [String :AnyObject] = ["userid" : userID! as AnyObject , "basketname" : basketname as AnyObject ]

            let dbref = FIRDatabase.database().reference()
            dbref.child("BasketList").childByAutoId().setValue(postitem)

            self.Basketdata2()



            let appearance = SCLAlertView.SCLAppearance(
                kDefaultShadowOpacity: 0,
                showCloseButton: false
            )

            let alertView = SCLAlertView(appearance: appearance)
            alertView.showTitle(
                "Saved", // Title of view
                subTitle: "", // String of view
                duration: 2.0, // Duration to show before closing automatically, default: 0.0
                completeText: "Done", // Optional button value, default: ""
                style: .success, // Styles - see below.
                colorStyle: 0xA429FF,
                colorTextButton: 0xFFFFFF
            )




        } else {


            let alert = SCLAlertView()
            alert.showError("Oops!", subTitle: "Basket name should not be empty")

            self.tableviewbasket.reloadData()

        }

    }
    alert.addButton("Cancel"){


    }
    alert.showEdit("Add basket", subTitle: "Please enter your basket name")




}

func Basketdata2() {
    HUD.show(.labeledProgress(title: "Loading...", subtitle: ""))

    let databaseref = FIRDatabase.database().reference()
    var userID = FIRAuth.auth()?.currentUser?.uid

    if userID == nil {

        userID = userfbid
    }

    databaseref.child("BasketList").queryOrdered(byChild: "userid").queryEqual(toValue: userID!).observeSingleEvent(of: .value, with: { (snapshot) in

        if snapshot.exists() {

            self.tableviewbasket.backgroundView = nil;
            HUD.hide()

        }  else {

            HUD.hide()


            self.tableviewbasket.setContentOffset(CGPoint(x : 0, y: -98), animated: true)


            if (self.BasketItemList.count == 0) {

                // tableView is empty. You can set a backgroundView for it.
                let label = UILabel(frame: CGRect(x: 5, y: 0, width: self.tableviewbasket.bounds.size.width, height:self.tableviewbasket.bounds.size.height))
                label.text = "The best preparation for tomorrow \n is doing your best today.\n Please create your first basket."
                label.textColor = UIColor.black;
                label.textAlignment = .center
                label.numberOfLines = 4
                label.sizeToFit()
                label.font = UIFont(name: "AvenirNext-Regular", size: 16.0)
                self.tableviewbasket.backgroundView = label;
                self.tableviewbasket.separatorStyle = .none;

            }

        }

    })
}


  func Basketdata() {

    HUD.show(.labeledProgress(title: "Please wait...", subtitle: ""))

    self.BasketItemList.removeAll()
    self.Basketid.removeAll()

    let databaseref = FIRDatabase.database().reference()
    let userID = FIRAuth.auth()?.currentUser?.uid

    databaseref.child("BasketList").queryOrdered(byChild: "userid").queryEqual(toValue: userID!).observeSingleEvent(of: .value, with: { (snapshot) in

        if snapshot.exists() {

            databaseref.child("BasketList").queryOrdered(byChild: "userid").queryEqual(toValue: userID!).observe(.childAdded, with: {
                (snapshot) in



                if let dictionary = snapshot.value as? [String : AnyObject] {


                    let basketitem = BasketList(text : "")
                    basketitem.setValuesForKeys(dictionary)

                    self.BasketItemList.append(basketitem)
                    self.Basketid.append(snapshot.key)
                    DispatchQueue.main.async {

                        if !self.BasketItemList.isEmpty {

                            HUD.hide()
                            self.tableviewbasket.reloadData()

                        }

                    }


                } else {

                    self.tableviewbasket.reloadData()
                    HUD.hide()
                }


            })




        }  else {

            if (self.BasketItemList.count == 0) {

                // tableView is empty. You can set a backgroundView for it.
                let label = UILabel(frame: CGRect(x: 5, y: 0, width: self.tableviewbasket.bounds.size.width, height:self.tableviewbasket.bounds.size.height))
                label.text = "The best preparation for tomorrow \nis doing your best today"
                label.textColor = UIColor.black;
                label.textAlignment = .center
                label.numberOfLines = 2
                label.sizeToFit()
                label.font = UIFont(name: "AvenirNext-Regular", size: 16.0)
                self.tableviewbasket.backgroundView = label;
                self.tableviewbasket.separatorStyle = .none;

            }


            HUD.hide()


        }

    })




}

有人可以帮助我了解我的代码有什么问题吗?谢谢!

Can someone help me understand what is wrong with my code? Thanks!

我引用此线程没有任何运气:使用UITableViewController cellForRowAtIndexPath获取重复的单元格

I have referred this thread without any luck: Getting duplicate cells with UITableViewController cellForRowAtIndexPath

同样,当我走出该视图并转到同一视图时,重复值也会被取消.

Edit 2: Also, when I come out of that view and go to the same view, the duplicate values are vansihed.

尝试答案没有任何成功.

Edit 3: Tried the answer without any success.

推荐答案

请按照以下步骤操作:

  1. 从Firebase数据库获取数据时,首先将cellForRow方法中使用的所有对象都删除到数组中.在您的情况下,我认为它应该是Bucket数组(不确定).

  1. When you'r getting data from firebase db, first remove your array all objects that you'r using in the cellForRow method. In your case i think it should be array of Bucket (not sure).

将数据分配给您的对象

重新加载表格视图.

数据复制的原因.

让您的存储桶具有2个值,并将其存储在DB中.当您从数据库中获取数据时,它会为您提供所有值,即1,2,3.现在添加这些,现在您的数组将为1,2,1,2,3.

let your bucket have 2 values and it is stored inDB. When you fetch data from DB it gives you all the values i.e. 1,2,3. Now you adds these now your array will be 1,2,1,2,3.

这就是您的情况.

这篇关于第一次获取重复的tableview单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆