2016-09-26 26 views
0

我试图运行一个独特的功能时,每个部分的每一行中单击按钮。 问题例如,如果我在3部分中有3行,并且配置第一行以在按下按钮时运行函数,则所有3部分的第一行运行相同的函数。我试图实现为不同部分中的所有行运行独特的功能。Swift 3:如何在表视图的多个部分使用动作按钮?

这是我的tableView代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: languageID, for: indexPath) as! LanguageTableViewCell 

    switch indexPath.row { 
    case 0: 
     cell.phraseLBL.text = "description 1" 
     cell.playBtn.tag = indexPath.row 
     cell.playBtn.addTarget(self, action: #selector(PhraseVC.pressPlay), for: .touchUpInside) 

    case 1: 
     cell.phraseLBL.text = "description 2" 
     cell.playBtn.tag = indexPath.row 
     cell.playBtn.addTarget(self, action: #selector(PhraseVC.pressPlay), for: .touchUpInside) 

    case 2: 
     cell.phraseLBL.text = "description 3" 
     cell.playBtn.tag = indexPath.row 
     cell.playBtn.addTarget(self, action: #selector(PhraseVC.pressPlay), for: .touchUpInside) 
    default: 
     break 
    } 

    return cell 
} 

这是ButtonIBAction

@IBAction func pressPlay(sender: UIButton){ 

     switch sender.tag { 
     case 0: 
      print("button 1 pressed") 

     case 1: 
      print("button 2 pressed") 

     case 2: 
      print("button 3 pressed") 

     case 3: 
      print("button 4 pressed") 

     case 4: 
      print("button 5 pressed") 
     default: 
      break; 
     } 
    } 

回答

3

你可以像

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: languageID, for: indexPath) as! LanguageTableViewCell 

    switch indexPath.row { 
    case 0: 
     cell.phraseLBL.text = "description 1" 


    case 1: 
     cell.phraseLBL.text = "description 2" 

    case 2: 
     cell.phraseLBL.text = "description 3" 

    default: 
     break 
    } 

    cell.playBtn.tag = indexPath.row 
    cell.playBtn.addTarget(self, action: #selector(PhraseVC.pressPlay(_:)), for: .touchUpInside) 


    return cell 
} 

,并调用方法

@IBAction func pressPlay(_ sender: UIButton){ 

    let touchPoint = sender.convert(CGPoint.zero, to:maintable) 
    // maintable --> replace your tableview name 

    let clickedButtonIndexPath = mainTable(forRowAtPoint: touchPoint) 



} 
0

您可以设定每个小区的指数路径,而不是标签。 IndexPath由部分和行组成。通过检查按钮属于哪个部分和哪一行,您可以唯一标识正确的功能。

相关问题