首页 文章

如何为Swift中不同的TableView单元格中的按钮提供不同的标签

提问于
浏览
2

我正在开发一个应用程序,用户可以将条目写入不同的主题,然后可以为条目提供上下点 . 我在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
    }
}

我的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
}

2 回答

  • 2

    也许终于找到了一个问题 . 当我在我的项目中重现问题时,我意识到 downcasting to 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)")
        ...
    }
    
  • 0

    If you have perform action on button click in tableview then try this code you don't worry about tag ..

    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))")
     }
    

    If my answer help you then give vote. thank you..

相关问题