2016-09-26 6 views
0

私は、各セクションの各行でボタンがクリックされたときにユニークな機能を実行しようとしています。 たとえば、3つのセクションに3行があり、ボタンを押したときに関数を実行するように最初の行を構成すると、3つのセクションすべての最初の行が同じ関数を実行します。私は、異なるセクションのすべての行に対して一意の関数を実行することを達成しようとしています。スイフト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はセクションと行で構成されます。ボタンがどのセクションとどの行にあるかを調べることによって、正しい機能を一意に識別することができます。あなたは