ios - 如何创建 segue 或新的 View Controller 以显示在不同的 View Controller 上

标签 ios swift segue

我正在尝试使用 swift 2 创建一个应用程序,该应用程序将让用户输入名称,在用户添加客户名称后,我希望用户能够单击该名称并将其带到另一个页面,其中他们可以看到细胞中含有什么。 这就是我所拥有的,但我不确定如何创建新的 segue 或 View Controller 。所有名称都存储在 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{
}

最佳答案

在你的 Storyboard中

在您的 Storyboard 中,您需要在要从中继续的 viewController 之间拖动关系。在您的例子中,从 ViewControllerViewController2。然后选择该关系并转到“属性检查器”并添加标识符。

在您的代码中

在您的 tableView didSelectRowAtIndexPath 中添加这一行:

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

添加这个segue函数

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"
        }
    }

然后当您点击 ViewController 中的一行到您的 ViewController2 时,您应该能够继续

在你的 Storyboard中

在您的 Storyboard 中,您需要在要从中继续的 viewController 之间拖动关系。在您的例子中,从 ViewControllerViewController2。然后选择该关系并转到“属性检查器”并添加标识符。

在您的代码中

在您的 tableView didSelectRowAtIndexPath 中添加这一行:

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

添加这个segue函数

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"
        }
    }

然后当您点击 ViewController 中的一行到您的 ViewController2 时,您应该能够继续

更新

您的代码示例

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
}

如果你这样做,它就会起作用。

关于ios - 如何创建 segue 或新的 View Controller 以显示在不同的 View Controller 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120335/

相关文章:

ios - 如何在 swift 中避免循环 segues

ios - 仅使用代码(无 Segue)呈现带有自定义动画的 View Controller

ios - 如何从 Google API 获取仅与健康相关的数据?

ios - Metal 计算着色器 : setting alpha to zero does not yield complete transparency

ios - 更改 App delegate 中的背景颜色

swift - AVAudioPlayer 不播放音频文件 - swift

ios - UIWebView 从 NSString 加载 PDF 字节

ios - 苹果登录后注销

ios - UITableView reloadRowsAtIndexPaths 不断重新加载单元格

ios - unwind segue 将数据传递给不同的 View Controller