如何使单元格可点击,单元格上的按钮也可以在 swift 中点击

How to make cell clickable also the buttons on cell will be clickable in swift

我在情节提要中使用了tableview。在此表格视图中,我添加了单元格。 每个行单元格都包含标签和一些按钮。

现在:

我想让行和单元格上的按钮都可以点击。

我尝试过使用故事板,但它不起作用。

你的错误是你将一个按钮直接拖到你的 UIViewController 上,这是行不通的。因为那是一个原型细胞。

你能做的是

  1. 为此按钮设置一个标签,例如 11
  2. cellForRowAtIndex

    中添加目标
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
        let  button = cell.viewWithTag(11) as? UIButton
        if button != nil{
            button?.addTarget(self, action: "clicked:", forControlEvents: UIControlEvents.TouchUpInside)
        }
        return cell
    }
    
  3. 获取按钮操作和索引

    func clicked(sender:UIButton){
       let point = sender.convertPoint(CGPointZero, toView:self.tableView)
        let indexPath = self.tableView.indexPathForRowAtPoint(point)
       println("Clicked \(indexPath!.row)")
    }