在我的 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/