web-dev-qa-db-ja.com

UITableViewでセルの選択を検出する方法-Swift

didSelectRowAtIndexPathまたは同様のものをアプリに実装する方法を考えているだけです。複数の動的なセルを含むテーブルビューがあり、基本的に特定のセルが選択されたらビューを変更します。

Obj-Cでそれを回避することはできますが、GoogleにはSwiftを支援するものは何もありません!私はまだ学んでいるので、助けていただければ幸いです

19
Alex

SwiftではdidSelectRowAtIndexPathを使用できます。

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    NSLog("You selected cell number: \(indexPath.row)!")
    self.performSegueWithIdentifier("yourIdentifier", sender: self)
}

Swift 3の場合

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    NSLog("You selected cell number: \(indexPath.row)!")
    self.performSegueWithIdentifier("yourIdentifier", sender: self)
}

UITableViewDelegateを必ず実装してください。

32
Christian Wörz

これは、cellForRow、numberOfRowsInSectionおよびnumberOfSectionsInTableを実装した後、UITableViewセルから他のView Controllerにセグメンテーションする方法です。

_//to grab a row, update your did select row at index path method to:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    NSLog("You selected cell number: \(indexPath.row)!");

    if indexPath.row == 1 {
        //THE SEGUE 
        self.performSegue(withIdentifier: "goToMainUI", sender: self)
    }
}
_

出力:You selected cell number: \(indexPath.row)!

ストーリーボードのセグエの識別子を関数の識別子に一致させることを忘れないでください(例:goToMainUI)。

3
WHC