【问题标题】:How to give different tags to buttons in different TableView cells in Swift如何在 Swift 中为不同 TableView 单元格中的按钮赋予不同的标签
【发布时间】:2017-02-09 20:53:51
【问题描述】:

我正在开发一个应用程序,用户可以在其中编写不同主题的条目,然后可以放弃对条目的加分和减分。我在我的 tableViewController 中使用了这个函数:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

我在这个函数的末尾添加了这两行:

cell.plusButton.tag = indexPath.row
cell.minusButton.tag = indexPath.row

所以这应该给 tableView 中的每个按钮一个标签,以便它与那个单元格的 indexpath.row 相同,我错了吗?因为当我尝试调用按钮时,它们的所有标签都相同并且等于 0。我怎样才能给它们不同的标签?这样就没有办法了吗?

这是我想要调用按钮时的代码:

@IBAction func plus(sender: AnyObject) {

    print(self.tag)

    let ref = FIRDatabase.database().reference().child("topics/"+topicClicked+"/"+entriesArrayTwo[self.tag])

    var value = Int()
    var date = String()
    var user = String()
    var votedDown = [""]
    var votedUp = [""]

    ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
        let dict = snapshot.value as! [String: AnyObject]

        value = dict["point"] as! Int
        date = String(dict["date"]!)
        user = String(dict["user"]!)
        votedUp = dict["votedUp"] as! NSArray as! [String]
        votedDown = dict["votedDown"] as! NSArray as! [String]

        var tempBool = false
        var temp = -1

        for uid in votedDown {
            temp = temp + 1

            if uid == FIRAuth.auth()?.currentUser?.uid {
                votedDown.removeAtIndex(temp)
                tempBool = true
            }
        }

        if tempBool == false {
            votedUp.append((FIRAuth.auth()?.currentUser?.uid)!)
        }

        ref.setValue(["point": value+1, "date": date, "user": user, "votedDown": votedDown, "votedUp": votedUp])

        self.point.text = String(value+1)
    })

    if minusButton.hidden == true {
        minusButton.hidden = false
    } else {
        plusButton.hidden = true
    }
}

My tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 函数如下:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "entryCell", for: indexPath) as! HubEntryTableViewCell

    if self.resultSearchController.isActive {

        let ref = FIRDatabase.database().reference().child("topics/"+topicClicked+"/"+filteredTableData[(indexPath as NSIndexPath).row])

        ref.observeSingleEvent(of: .value, with: { snapshot in

            let value = snapshot.value as? NSDictionary

            cell.point.text = String(describing: value!["point"]!)

            let postRef = FIRDatabase.database().reference().child("users/"+String(describing: value!["user"]!))

            postRef.observeSingleEvent(of: .value, with:  { snapshotTwo in

                let valueTwo = snapshotTwo.value as? NSDictionary

                cell.subInfo.text = String(describing: valueTwo!["name"]!)+" "+String(describing: valueTwo!["surname"]!)+" - "+String(describing: value!["date"]!)

            })


            })

        cell.entry.text = self.filteredTableData[(indexPath as NSIndexPath).row]

    } else {

        let ref = FIRDatabase.database().reference().child("topics/"+topicClicked+"/"+entriesArray[(indexPath as NSIndexPath).row])

        ref.observeSingleEvent(of: .value, with: { snapshot in

            let value = snapshot.value as? NSDictionary

            cell.point.text = String(describing: value!["point"]!)

            let postRef = FIRDatabase.database().reference().child("users/"+String(describing: value!["user"]!))

            postRef.observeSingleEvent(of: .value, with:  { snapshotTwo in

                let valueTwo = snapshotTwo.value as? NSDictionary

            cell.subInfo.text = String(describing: valueTwo!["name"]!)+" "+String(describing: valueTwo!["surname"]!)+" - "+String(describing: value!["date"]!)

            })

            let votedUpRef = ref.child("votedUp")

            votedUpRef.observeSingleEvent(of: .value, with: { upSnapshot in

                var tempDict = snapshot.value as! [String: AnyObject]
                let tempArray = tempDict["votedUp"] as! [String]

                for uid in tempArray {

                    if String(uid) == FIRAuth.auth()?.currentUser?.uid {

                        cell.plusButton.isHidden = true

                    }

                }

            })

            let votedDownRef = ref.child("votedDown")

            votedUpRef.observeSingleEvent(of: .value, with: { upSnapshot in

                var tempDict = snapshot.value as! [String: AnyObject]
                let tempArray = tempDict["votedDown"] as! [String]

                for uid in tempArray {

                    if String(uid) == FIRAuth.auth()?.currentUser?.uid {

                        cell.minusButton.isHidden = true

                    }

                }

            })

        })

        cell.entry.text = self.entriesArray[(indexPath as NSIndexPath).row]

    }

    cell.plusButton.tag = (indexPath as NSIndexPath).row
    cell.minusButton.tag = (indexPath as NSIndexPath).row

    // NEW METHOD TO GET THE BUTTON

    let check1: UIButton = (cell.viewWithTag(1) as! UIButton)
    let check2: UIButton = (cell.viewWithTag(2) as! UIButton)
    check1.addTarget(self, action: #selector(HubEntriesTableViewController.CloseMethod(_:event:)), for: .touchDown)
    check2.addTarget(self, action: #selector(HubEntriesTableViewController.CloseMethod1(_:event:)), for: .touchDown)

    // Configure the cell...

    return cell
}

【问题讨论】:

  • 分享我们粘贴您的整个代码与您在按钮单击中所做的事情
  • 我指的是一个数据库,其中孩子来自按下按钮的标签。像这样:让 ref = FIRDatabase.database().referance().child("self.tag"),但在我的情况下标签始终为 0
  • set cell.buttonPlus.Tag = indexpath.row+UniqueNumber set cell.buttonMinus.Tag = indexpath.row+UniqueNumber(different) 就可以轻松搞定了。
  • @DevThakur 你能说得更具体点吗?什么是 uniqueNumber 和 buttonPlusTag?它们是不同的变量吗?
  • Like For减号按钮唯一编号可能是(1000)和加号我将使用(5000)现在我可以设置标签,如cell.plusbutton.tag = indexpath.row+(5000),我什么时候会明白了,我可以通过 uniqueNumber 减少 button.tag 示例:标签将是 50001(对于 indexpath.row ==1) newTag = btnTag-(UniqueNumber)

标签: ios swift firebase tableview firebase-realtime-database


【解决方案1】:

也许终于发现了一个问题。当我在我的项目中重现该问题时,我意识到 向下转换为 UIButton 丢失了。

所以在HubEntryTableViewCell 子类中更新方法如下:

@IBAction func plus(sender: AnyObject) {

    // self.tag, if called from UITableViewCell subclass, is rather cell's tag, not button's tag

    let button = sender as! UIButton
    print("button.tag = \(button.tag)")
    ...
}

【讨论】:

  • 我只有一节
  • 它正确地将 indexpath.rows 显示为 0,1,2 等等。没有问题。同样,当我“打印(cell.plusButton.tag)”时,它会正确给出 0,1,2... @pedrouan
【解决方案2】:

如果您在 tableview 中对按钮单击执行了操作,那么试试这个代码,您不必担心标签 ..

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Eventcell", forIndexPath: indexPath)
   let check1: UIButton = (cell.viewWithTag(11) as! UIButton)
   let check2: UIButton = (cell.viewWithTag(12) as! UIButton)   
    check1.addTarget(self, action: #selector(EventListController.CloseMethod(_:event:)), forControlEvents: .TouchDown)
    check2.addTarget(self, action: #selector(EventListController.CloseMethod1(_:event:)), forControlEvents: .TouchDown)
    return cell
 }
  @IBAction func CloseMethod(sender: UIButton, event: AnyObject) {
        let touches = event.allTouches()!
        let touch = touches.first!
        let currentTouchPosition = touch.locationInView(self.Eventlisttable)
        let indexPath = self.Eventlisttable.indexPathForRowAtPoint(currentTouchPosition)!
        print("\(Int(indexPath.row))")

  }
  @IBAction func CloseMethod1(sender: UIButton, event: AnyObject) {
        let touches = event.allTouches()!
        let touch = touches.first!
        let currentTouchPosition = touch.locationInView(self.Eventlisttable)
        let indexPath = self.Eventlisttable.indexPathForRowAtPoint(currentTouchPosition)!
        print("\(Int(indexPath.row))")
 }

如果我的回答对您有帮助,请投票。谢谢你..

【讨论】:

  • 我要做的就是在单击相应按钮时从数据库中增加和减少条目的“点”值。我的意思是,当按下 + 按钮时,我想增加 1,而当按另一种方式单击减号时。
  • 那么您可以在 CloseMethod 中为该特定单元格执行此操作。在我的情况下,我必须在 tableview 中为特定的单元格数据执行一些操作......我的表是 Eventlisttable 。
  • 什么是closeMethod和closeMethod1?他们是不同的按钮吗?还有 cell.viewWithTag(11) 和 (12),它们是什么?
  • 是的,两者都是 tableview 中的不同按钮,我从标签访问该按钮。
  • 你能看一下我编辑原始帖子的代码吗?我应该在 CloseMethod func 中执行该代码吗?如果我用你的方法?
猜你喜欢
  • 1970-01-01
  • 2017-02-18
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多