JimmyLee
JimmyLee

Reputation: 569

UITableview function "DidselectRowAt" show to different target viewcontroller

I have a tableview, and I use didSelectRowAtIndexPath to filter which indexpath to which viewController.
I try to use following code, but I failed.
What's wrong with me.
Thanks.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    print("index:", indexPath.row)

    if indexPath.row != 0 || indexPath.row != 1 {
        //When index = 0 or 1, it also push to next vc.
        //I don't want index 0 or 1 to push next vc.
        let vc = ViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }

}

Upvotes: 0

Views: 161

Answers (2)

MhmdRizk
MhmdRizk

Reputation: 1721

It's a good practice to perform any UI action on the main Queue,

and also it's better to use (switch case) instead of (if else) to reduce the complexity of your code.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.row {
        case 0, 1 :
            break
        default :
            let vc = ViewController()
            DispatchQueue.main.async {
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
}

Upvotes: 0

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

Rookie mistake. You should be using && not ||.

if indexPath.row != 0 && indexPath.row != 1 {
    let vc = ViewController()
    self.navigationController?.pushViewController(vc, animated: true)
}

Or like @Anbu.karthik pointed out in the comments, the simpler and less confusing way.

if indexPath.row > 1 {
    let vc = ViewController()
    self.navigationController?.pushViewController(vc, animated: true)
}

Upvotes: 3

Related Questions