ios - 将核心数据从选定的表格单元格传递到新的 View Controller

标签 ios swift core-data

我正在尝试将数据(标题、成分、步骤、图像)从选定的表格单元格传递到新的 View Controller 。但我不知道该怎么做。我有很多错误,所以现在我重新开始。谁能帮我?我是编码新手。谢谢:-) 我的代码:

VIEWCONTROLLER.SWIFT

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!
    var recipes = [Recipe]()

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }

    override func viewDidAppear(animated: Bool) {
        fetchAndSetResults()
        tableView.reloadData()
    }

    func fetchAndSetResults(){
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        let context = app.managedObjectContext
        let fetchRequest = NSFetchRequest(entityName: "Recipe")

        do {
            let results = try context.executeFetchRequest(fetchRequest)
            self.recipes = results as! [Recipe]
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCellWithIdentifier("RecipeCell") as? RecipeCell {
            let recipe = recipes[indexPath.row]
            cell.configureCell(recipe)
            return cell
        } else {
            return RecipeCell()
        }
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "RecipeDetail") {
            //I WANT TO PASS THE DATA FROM THE TABLE CELL TO THE NEW VIEW CONTROLLER (RECIPEDETAILVC)
        }
    }

    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }

    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if (editingStyle == UITableViewCellEditingStyle.Delete) {

            let app = UIApplication.sharedApplication().delegate as! AppDelegate
            let context = app.managedObjectContext

            context.deleteObject(recipes[indexPath.row])
            app.saveContext()

            recipes.removeAtIndex(indexPath.row)
            tableView.reloadData()
        }
    }
}

创建食谱.SWIFT
class CreateRecipeVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var recipeTitle: UITextField!
    @IBOutlet weak var recipeIngredients: UITextField!
    @IBOutlet weak var recipeSteps: UITextField!
    @IBOutlet weak var recipeImage: UIImageView!
    @IBOutlet weak var addRecipeBtn: UIButton!

    var imagePicker: UIImagePickerController!

    override func viewDidLoad() {
        super.viewDidLoad()
        imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        recipeImage.layer.cornerRadius = 5.0
        recipeImage.clipsToBounds = true

    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

        imagePicker.dismissViewControllerAnimated(true, completion: nil)
        recipeImage.image = image

    }

    @IBAction func addImage(sender: AnyObject!) {
        presentViewController(imagePicker, animated: true, completion: nil)
    }

    @IBAction func createRecipe(sender: AnyObject!) {
        if let title = recipeTitle.text where title != "" {
            let app = UIApplication.sharedApplication().delegate as! AppDelegate
            let context = app.managedObjectContext
            let entity = NSEntityDescription.entityForName("Recipe", inManagedObjectContext: context)!
            let recipe = Recipe(entity: entity, insertIntoManagedObjectContext: context)
            recipe.title = title
            recipe.ingredients = recipeIngredients.text
            recipe.steps = recipeSteps.text
            recipe.setRecipeImage(recipeImage.image!)

            context.insertObject(recipe)

            do {
                try context.save()
            } catch {
                print("Could not save recipe")
            }

            self.navigationController?.popViewControllerAnimated(true)
        }
    }

}

RECIPEDETAILVC.SWIFT
import UIKit
import CoreData

class RecipeDetailVC: UIViewController {

    @IBOutlet weak var recipeImage: UIImageView!
    @IBOutlet weak var recipeTitle: UILabel!
    @IBOutlet weak var recipeIngredients: UILabel!
    @IBOutlet weak var recipeSteps: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        //I WANT TO DISPLAY THE CORE DATA INFORMATION FROM THE TABLE CELL I SELECTED.
    }
}

RECIPECELL.SWIFT
class RecipeCell: UITableViewCell {

    @IBOutlet weak var recipeTitle: UILabel!
    @IBOutlet weak var recipeImage: UIImageView!

    func configureCell(recipe: Recipe) {
        recipeTitle.text = recipe.title
        recipeImage.image = recipe.getRecipeImage()
    }

}

最佳答案

您需要跟踪该人单击了哪个项目。

var mySelection: Int?
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    mySelection = indexPath.row
}

然后,在进行 segue 时使用它。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)     {
    if (segue.identifier == "RecipeDetail") {
        //I WANT TO PASS THE DATA FROM THE TABLE CELL TO THE NEW VIEW CONTROLLER (RECIPEDETAILVC)
        let recipeDetailControler = segue.destinationViewController as! RecipeDetailViewController

        if let mySelection = mySelection {
            let recipe = recipes[mySelection]
            // add this function to your
            recipeDetailControler.configureRecipeData(recipe)
        }
    }
}

将此函数添加到 RecipeDetailViewController:
func configureRecipeData(recipe: Recipe) {

    // IMPLEMENT ME

}

关于ios - 将核心数据从选定的表格单元格传递到新的 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36116119/

相关文章:

ios - 如何在运行时检查核心数据属性类型?

iphone - 核心数据一对多关系: List all related objects as section header in UITableView

ios - 具有自定义 View 和弱引用的 UIViewController

objective-c - 类别类方法上的 performSelector

swift - estimatedRowHeight API 有时会破坏自定义单元格

swift - 如何在 swift3 alamofire 中设置 Content-Type

ios - UIAlertController 'UIAlertAction' 标签/用户数据或 Swift 中的任何内容

swift - 如何从 Swift 中的 CoreData 实体关系中获取分段数据

ios - 如何正确更新AUSampler的loadInstrument属性?

ios - 如何在 iOS 代码中创建和访问 UI