Amundsen93
Amundsen93

Reputation: 13

Edit- UITableView cell buttons action delegate- Swift 4

Edit-

I have 8 different ViewControllers and want each of the cell push it so should go to the ViewControllers 1, etc.

This code works good for me to delegate to another view controller with segue, hope this code will help you

Edit-

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if isPurchased() {
        return freeQuotes.count
    }
    return freeQuotes.count + 1
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    if indexPath.row < freeQuotes.count {

        cell.textLabel?.text = freeQuotes[indexPath.row]
        cell.textLabel?.font = UIFont(name: (cell.textLabel?.font.fontName)!, size:20)
        cell.textLabel?.textColor = cell.textLabel?.textColor = colorLiteral
        cell.accessoryType = .disclosureIndicator


    } else {

        cell.textLabel?.text = ""
        cell.textLabel?.font = UIFont(name: (cell.textLabel?.font.fontName)!, size:20)
        cell.textLabel?.textColor = colorLiteral
        cell.accessoryType = .disclosureIndicator

    }
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == freeQuotes.count {

    }
     performSegue(withIdentifier: segueIndenidentity[indexPath.row], sender: self)

}

Upvotes: 0

Views: 152

Answers (1)

amin
amin

Reputation: 313

It will be handle with switch case :

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

   switch indexPath.row {
    case 1:
        // go to first view controller
    case 2:
        // go to second view controller
    case 3:
        // go to third view controller
    case 4:
        // go to fourth view controller
    case 5:
        // go to fifth view controller
    default:
        print("no vc")
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    super.prepare(for: segue, sender: sender)

    switch(segue.identifier ?? ""){
    case "MySegueIdentifier":

        guard let selectedCell = sender as? MainTableViewCell
            else{
                fatalError("Unexpected Sender \(String(describing: sender))")
        }
        guard let indexPath = mainTableView.indexPath(for: selectedCell)
            else{
                fatalError("The selected cell is not being displayed by the table")
        }

        switch indexPath.row {
        case 0:
            let nextVC = segue.destination as! FirstViewController
        case 1:
            let nextVC = segue.destination as! SecondViewController
        default:
            print("Nothing")
        }

    default:
        fatalError("Unexpected Segue Identifier \(String(describing: segue.identifier))")
    }
}

Upvotes: 2

Related Questions