2016-11-26 17 views
0

ここで初心者を完了して、TabelViewCellのボタンを押すとその行番号を表示しようとしています。Swift - UIButtonが押されたときに別のクラスの関数が呼び出されない

var myTableViewController: tableViewController? 

    @IBOutlet var addButton: UIButton! 


    @IBAction func addButtonPressed(_ sender: Any) { 
    myTableViewController?.addCellToHome(self) //call add function 
} 

そしてtableViewControllerから:ここで

がtableViewCellからのコードです

func addCellToHome(_ cell: UITableViewCell) //specifies what is to be done when addButton is pressed 
{ 

    let row = tableView.indexPath(for: cell) 

    print(row as! String) 
} 

誰かが私が間違ってやっているものを私に教えてくださいことはできますか?私はaddCellToHomeの中にブレークポイントを挿入し、決して呼び出されないことが判明しました。完了しました。

ありがとうございます。

+0

(http://stackoverflow.com/questions/28894765/ios-swift-button-action-in-table-view-cell)[テーブルビューセル内のiOSスウィフトボタンアクション]の可能な重複 – DogCoffee

+0

IBActionが呼び出されていますか? – TheValyreanGroup

+0

@TheValyreanGroupはい、間違いありません。 tableViewCellの元のコードに 'self.addButton.isEnabled = false'があり、ボタンが押されるとグレーアウトされます。 – qunayu

答えて

-1

メモリに現在のものを使用する代わりに、tableViewControllerの新しいインスタンスを作成しています。 VCの新しいインスタンスを作成する代わりに、以下を試してください。

@IBAction func addButtonPressed(_ sender: Any) { 
    let storyboard = UIStoryboard(name: "Main", bundle: nil) 
    let myTableViewController = storyboard.instantiateViewController(withIdentifier :"tableViewController") as! tableViewController 
    myTableViewController?.addCellToHome(self) //call add function 
} 

あなたが他のメソッドの呼び出しで、このVCを使用する予定の場合は、あなたのオリジナルのポストに行ったように、あなたはまた、クラス内の任意の関数のmyTableViewController外を初期化することができます。

+0

Gotエラー: 'UITableViewController'タイプの値に 'addCellToHome'というメンバーがありません – qunayu

+0

'として変更! UITableViewController'を 'として'! tableViewController'、またはクラス名が何であっても。また、 'instantiate'メソッドの' withIdentifier'部分をストーリーボードのVCのidに変更してください。 – TheValyreanGroup

+0

@qunayuうれしい! – TheValyreanGroup

0

MyCellDelegateのようなセルの代理プロトコルを作成する必要があります。

See guide to delegates

または、あなたのtableViewControllerのcellForRow(at: IndexPath)からセルボタンにアクションを追加します。

See guide to button actions

関連する問題