如何检测swift 2中单击的表格单元格

时间:2016-04-17 09:48:20

标签: ios swift2

我正在开发app,用户将在一个单元格中选择两张图片中的一张。我的原型单元看起来像:

prototype cell

如何检测用户何时按下投票按钮选择了哪个单元格?

我的tableView代码:

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

        let cellIdentifier = "NewTableViewCell"
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! NewTableViewCell

        //For left image
        if let url:NSURL? = NSURL(string: self.polls[indexPath.row].poll_photo1 ){
            cell.leftImage.sd_setImageWithURL(url)
        }
        //For right image
        if let url:NSURL? = NSURL(string: self.polls[indexPath.row].poll_photo2 ){
            cell.rightImage.sd_setImageWithURL(url)

        }

        //For user picture
        if let url:NSURL? = NSURL(string: self.polls[indexPath.row].users[0].user_photo ){
            cell.userPicture.sd_setImageWithURL(url)
        }

        // gets username and text
        cell.userName.text=self.polls[indexPath.row].users[0].user_name
        cell.description.text = self.polls[indexPath.row].poll_textfield

        return cell
    }

我的网址API:

enter image description here

2 个答案:

答案 0 :(得分:4)

我假设您的自定义表格视图单元格NewTableViewCell有一个投票按钮的插座 只需使用voteButton标记indexPath.row,然后在目标函数中获取标记,如下所示。当您按下投票按钮时,您将了解哪个单元格voteButton被点击了

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

    let cell = tableView.dequeueReusableCellWithIdentifier("NewTableViewCell") as! NewTableViewCell

    //Tagging with indexPath.row
    cell.voteLeftButton.tag = indexPath.row
    cell.voteRightButton.tag = indexPath.row


    //This is the latest Swift 2.2 syntax for selector. If you are using the older version of Swift, Kindly check the selector syntax and make changes accordingly
    cell.voteLeftButton.addTarget(self, action: #selector(voteLeftButtonPressed), forControlEvents: .TouchUpInside)
    cell.voteRightButton.addTarget(self, action: #selector(voteRightButtonPressed), forControlEvents: .TouchUpInside)
    return cell

}

func voteLeftButtonPressed(sender:UIButton){

    print("Left Button Table cell clicked is \(sender.tag)")

}

func voteRightButtonPressed(sender:UIButton){

    print("Right Button Table cell clicked is \(sender.tag)")

}

答案 1 :(得分:0)

在单元格配置方法中将目标/操作添加到按钮中,如下所示:

 let tap : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(YourController.tapAction(_:)))

然后实现tapAction方法

func tapAction(sender : UITapGestureRecognizer)
  {

    if sender.state != UIGestureRecognizerState.Ended
    {
        return

    }
    let btn = sender.view as! UIButton

    let pointTo : CGPoint  = CGRectOffset(btn.bounds, btn.frame.size.width/2, btn.frame.size.height/2).origin;
    let buttonPosition : CGPoint  = btn.convertPoint(pointTo, toView: self.tableView)

    let indexPath = self.tableView.indexPathForRowAtPoint(buttonPosition)


    ...

}