简体   繁体   中英

ViewController with a tableview to another view controller

I want to select a row and then index this to another view controller. I have created a function which is "didselectrow" however this is not navigating me to the next view controller. Any solutions or help would be much appreciated.

import UIKit import CoreData

class CoreViewController: UIViewController, UITableViewDelegate, 
UITableViewDataSource {

@IBOutlet var tableView: UITableView!

var users : [Users] = []

override func viewDidLoad() {
    super.viewDidLoad()


    tableView.dataSource = self
    tableView.delegate = self

    // Do any additional setup after loading the view.
}

//view the data on the table view appear 

override func viewDidAppear(_ animated: Bool) {

    // get data 
    getData()

    //reload data
    tableView.reloadData()
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return users.count
}

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

    let cell = UITableViewCell()
    let user  = users[indexPath.row]

    if user.isimportant
    {
        cell.textLabel?.text = "👍\(user.username!)"
    }
    else
    {
        cell.textLabel?.text = user.username! //entity name in textlabel
    }
    return cell

}

func getData()
{
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    do{
        users  = try context.fetch(Users.fetchRequest())
    }
    catch {
        print ("Fetching Failed ")
    }

}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    if editingStyle == .delete
    {
        let user = users[indexPath.row]
        context.delete(user)

        (UIApplication.shared.delegate as! AppDelegate).saveContext()

        do{
            users  = try context.fetch(Users.fetchRequest())
        }
        catch {
            print ("Fetching Failed ")
        }
    }
    tableView.reloadData()
}


func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: QuestionsViewController) {
    performSegue(withIdentifier: "questionview", sender: nil)
}




/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

Try this!

Call the segue from

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {

        self.performSegueWithIdentifier("questionview", sender: nil)

    }

 override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "questionview") {
        let viewController:ViewController = segue!.destinationViewController as ViewController
        let indexPath = self.tableView.indexPathForSelectedRow()
        viewController.mydata = self.myarray[indexPath.row]
    }
}

you need to call in didselectAtIndexPathRow

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    performSegue(withIdentifier: "questionview", sender: nil)
}

Your didSelectRow method is not correct what you have done is passed QuestionsViewController as type for indexpath

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: QuestionsViewController) {
    performSegue(withIdentifier: "questionview", sender: nil)
}

It should be,

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "questionview", sender: nil)
    }

You can Try this

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

    let cell = self.tableView.cellForRow(at: indexPath as IndexPath)

self.performSegue(withIdentifier: "yoursegueIdentifier", sender: nil)

}

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

    let theDestinationVC = (segue.destination as! NextVC)

}

Check out the link given below. This will help you building a table view from scratch.

https://code.tutsplus.com/tutorials/ios-from-scratch-with-swift-table-view-basics--cms-25160

step 1 : Add 2 View Controller

Step 2 : Add Table View in 1st viewController

Step 3 : add tableview cell in Table view (give identifier "cell")

Step 4 : Check table view Property

步骤4图片

Step 5 : Prepare segue way (1st view controller to 2nd View Controller)

如何准备这首歌

Step 6 : here is full code

 class CoreViewController: UIViewController, UITableViewDelegate,
UITableViewDataSource {

    @IBOutlet var tableView: UITableView!

    var users : [Users] = []

    override func viewDidLoad() {
        super.viewDidLoad()


        tableView.dataSource = self
        tableView.delegate = self

        // Do any additional setup after loading the view.
    }

    //view the data on the table view appear

    override func viewDidAppear(_ animated: Bool) {

        // get data
        getData()

        //reload data
        tableView.reloadData()
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return users.count
    }

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

        let cell = UITableViewCell()
        let user  = users[indexPath.row]

        if user.isimportant
        {
            cell.textLabel?.text = "\(user.username!)"
        }
        else
        {
            cell.textLabel?.text = user.username! //entity name in textlabel
        }
        return cell

    }

    func getData()
    {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        do{
            users  = try context.fetch(Users.fetchRequest())
        }
        catch {
            print ("Fetching Failed ")
        }

    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        if editingStyle == .delete
        {
            let user = users[indexPath.row]
            context.delete(user)

            (UIApplication.shared.delegate as! AppDelegate).saveContext()

            do{
                users  = try context.fetch(Users.fetchRequest())
            }
            catch {
                print ("Fetching Failed ")
            }
        }
        tableView.reloadData()
    }


    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: QuestionsViewController) {
        performSegue(withIdentifier: "questionview", sender: nil)
    }



    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "questionview" {

        }
    }
    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM