如何使单元格可单击也可以在swift

时间:2015-06-03 05:58:07

标签: ios swift tableview

我在故事板中使用了tableview。在这个tableview中我添加了单元格。 每个行单元格都包含标签和一些按钮。

现在:

我想在可点击的单元格上创建行和可点击的按钮。

我尝试使用故事板,但它无效。

1 个答案:

答案 0 :(得分:3)

您的错误是您将一个按钮直接拖到您的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)")
    }