简体   繁体   中英

How to create segue or new view controller to show on different view controller

I am trying create an app using swift 2, the app will have a user type in a name, after the user adds a clients name I want the user to be able to click on the name and take them to another page where they can see what the cell holds. This is what I have but I'm not sure how to create the new segue or view controller. All the name are being stored in CoreData.

View Controller:

import UIKit
import CoreData

class ViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!

    var people = [NSManagedObject]()

    @IBAction func addName(sender: AnyObject) {
        let alert = UIAlertController(title: "New Client",
            message: "Add a new client",
            preferredStyle: .Alert)

        let saveAction = UIAlertAction(title: "Save",
            style: .Default,
            handler: { (action:UIAlertAction) -> Void in
                let textField = alert.textFields!.first
                self.saveName(textField!.text!)
                self.tableView.reloadData()
        })

        let cancelAction = UIAlertAction(title: "Cancel",
            style: .Default) { (action: UIAlertAction) -> Void in
        }

        alert.addTextFieldWithConfigurationHandler {
            (textField: UITextField) -> Void in
        }

        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        presentViewController(alert,
            animated: true,
            completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Clients"
        tableView.registerClass(UITableViewCell.self,
            forCellReuseIdentifier: "Cell")
    }

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell =
        tableView.dequeueReusableCellWithIdentifier("Cell")

        let person = people[indexPath.row]

        cell!.textLabel!.text =
            person.valueForKey("name") as? String

        return cell!
    }

    func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
        // either present the view controller for new page or perform the Segue
        //self.people = self.tableView[indexPath.row]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func saveName(name: String) {
        //1
        let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext

        //2
        let entity =  NSEntityDescription.entityForName("Person",
            inManagedObjectContext:managedContext)

        let person = NSManagedObject(entity: entity!,
            insertIntoManagedObjectContext: managedContext)

        //3
        person.setValue(name, forKey: "name")

        //4
        do {
            try managedContext.save()
            //5
            people.append(person)
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        //1
        let appDelegate =
        UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext

        //2
        let fetchRequest = NSFetchRequest(entityName: "Person")

        //3
        do {
            let results =
            try managedContext.executeFetchRequest(fetchRequest)
            people = results as! [NSManagedObject]
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }
    }

ViewController2:

import Foundation

class ViewController2{
}

In your storyboard

In your storyboard you need to drag a relationship between the viewControllers that you want to segue from. In your case from ViewController to ViewController2 . Then select that relationship and go to the "Attributes inspector" and add an identifier.

In your code

In your tableView didSelectRowAtIndexPath add this line:

self.performSegueWithIdentifier("YOUR IDENTIFIER ID", sender: nil)

Add this segue function

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
    {
        // you can skip this line if you want, but good to have if you have multiple segues
        if (segue.identifier == "YOUR IDENTIFIER ID")
        {
            // create an instance to your second viewController
            let second = segue.destinationViewController as! ViewController2

            // now you can access variables and function in ViewController2 by using "second"
        }
    }

Then you should be able to to segue when you click on a row in your ViewController to your ViewController2

In your storyboard

In your storyboard you need to drag a relationship between the viewControllers that you want to segue from. In your case from ViewController to ViewController2 . Then select that relationship and go to the "Attributes inspector" and add an identifier.

In your code

In your tableView didSelectRowAtIndexPath add this line:

self.performSegueWithIdentifier("YOUR IDENTIFIER ID", sender: nil)

Add this segue function

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
    {
        // you can skip this line if you want, but good to have if you have multiple segues
        if (segue.identifier == "YOUR IDENTIFIER ID")
        {
            // create an instance to your second viewController
            let second = segue.destinationViewController as! ViewController2

            // now you can access variables and function in ViewController2 by using "second"
        }
    }

Then you should be able to to segue when you click on a row in your ViewController to your ViewController2

UPDATE

Your code example

func tableView(tableView: UITableView,didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.performSegueWithIdentifier("YOUR IDENTIFIER ID", sender: self.tableView[indexPath.row])
    }

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!)
{
     let secondViewController = segue.destinationViewController as! ViewController2
     // secondViewController = name of the instance to ViewController2
     // second = the name of a variable that you have created in ViewController2
    // sender is the value that was passed as a parameter from self.tableView[indexPath.row] in performSegueWithIdentifier. You have to check what this value consists
     secondViewController.second = sender
}

If you do it this way it will work.

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