swift - UItableview 中的 UIbutton,每个单元格中的每个按钮都有不同的操作

标签 swift uitableview uibutton

在我的 UITableView 中,我试图有一个按钮,它对每个单元格都有不同的操作,即链接到不同的 viewController,对于每个按钮,但我已经只有一个成功实现了它。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return courseTitle.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell

    cell.image_view.image = courseImages[indexPath.row]
    cell.title.text = courseTitle[indexPath.row]
    cell.tableButton.tag = indexPath.row
    cell.tableButton.addTarget(self, action: "Test", forControlEvents: UIControlEvents.TouchUpInside)

     return cell
}

@IBAction func Test(sender: AnyObject){

    self.performSegueWithIdentifier("SuccessfulLogin", sender: nil)

}

最佳答案

如果你只有几个单元格,你可以这样做:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell

    cell.image_view.image = courseImages[indexPath.row]
    cell.title.text = courseTitle[indexPath.row]
    cell.tableButton.tag = indexPath.row

    switch indexPath.row {

    case 0:
        cell.tableButton.addTarget(self, action: "TestA", forControlEvents: UIControlEvents.TouchUpInside)

    case 1:
        cell.tableButton.addTarget(self, action: "TestB", forControlEvents: UIControlEvents.TouchUpInside)

    case 2:
        cell.tableButton.addTarget(self, action: "TestC", forControlEvents: UIControlEvents.TouchUpInside)

    default:
        cell.tableButton.addTarget(self, action: "TestD", forControlEvents: UIControlEvents.TouchUpInside)
    }

    return cell
}

func TestA(sender: AnyObject){   // no need for @IBAction as you set the target action while setting the cell
    self.performSegueWithIdentifier("SuccessfulLogin", sender: nil)
}

func TestB(sender: AnyObject){
    print("Second button action")
}

func TestC(sender: AnyObject){
    print("Third button action")
}

func TestD(sender: AnyObject){
    print("All other buttons action")
}

关于swift - UItableview 中的 UIbutton,每个单元格中的每个按钮都有不同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38634593/

相关文章:

ios - 在 iOS (Flutter) 中使用 Firebase 和 Geolocator(或任何 Swift 插件)构建错误

ios - swift : align UILabel text in the top rather in the middle

ios - 使用 Swift 更改 UISlider 图像

ios - 在获取数据之前加载 TableView

ios - UITableView 自定义单元格数据在快速滚动时不匹配

iPhone UIView 动画禁用 UIButton subview

ios - Swift/IOS 重置 CollectionViewCell 中的 ImageView 缩放

ios - 如何在 iOS 中让 UITableView 变大

ios - 是什么导致 UIButton 标题周围的水平填充?

ios - 动画 UIButton 的标题更改