将核心数据值传递到文本字段中以进行编辑/保存 [英] Pass core data values into text fields for editing/saving

查看:61
本文介绍了将核心数据值传递到文本字段中以进行编辑/保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用Xcode的新手,很快就可以学习。我无法将核心数据从实体传递到文本字段/标签,然后用户可以选择编辑和保存记录。我的目的是当用户从 friendslistViewController.swift 单击tableView中的单元格时,将其带到 editViewController.swift 屏幕可编辑并保存记录。我想我需要实现 prepareforsegue 函数,但不确定如何实现?

I am a novice at using Xcode and swift and still learning. I am having trouble passing core data from entities into text fields/labels which the user can then choose to edit and save the record. My aim is when the user clicks on a cell in the tableView from friendslistViewController.swift it then brings them to the editViewController.swift screen to edit and save the record. I think I need to implement the prepareforsegue function, but not sure how to?

friendsViewController.swift (初始数据输入)

//
//  friendsViewController.swift
// 
//
//  Created by on 11/10/17.
//  Copyright © 2017. All rights reserved.
//

import UIKit
import CoreData

class friendsViewController: UIViewController {

        //OUTLETS


    @IBOutlet weak var firstName: UITextField!        
    @IBOutlet weak var lastName: UITextField!        
    @IBOutlet weak var genderSegControl: UISegmentedControl!        
    @IBOutlet weak var ageStepper: UIStepper!

    //AGECOUNT
    @IBOutlet weak var ageLabel: UILabel!        
    @IBOutlet weak var address: UITextField!

    var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    override func viewDidLoad() {
        super.viewDidLoad()    
        // Do any additional setup after loading the view.
    }

    //actions

    @IBAction func ageStepperStep(_ sender: UIStepper) {
        let step = Int(sender.value) // using an integer variable
        ageLabel.text = String(step)
        // label1.text = Int(sender.value).description
        // another way without using any integer variable
    }


    // TEST GENDER
    /*

        var gender : String
        if self.genderSegControl.selectedSegmentIndex == 0 {
            gender = "male"
        }
        else {
            gender = "female"
        }
        genderLabel.text! = gender

 */

   //SAVE FRIEND BUTTON
    @IBAction func saveFriendBtn(_ sender: Any) {

        if firstName.text != "" && lastName.text != "" {               

            var gender : String?
            if self.genderSegControl.selectedSegmentIndex == 0 {
                gender = "male"
            }
            else {
                gender = "female"
            }


            let newFriend = NSEntityDescription.insertNewObject(forEntityName: "Friends", into: context)
            newFriend.setValue(self.firstName.text, forKey: "firstName")
            newFriend.setValue(self.lastName.text, forKey: "lastName")
            newFriend.setValue(self.address.text, forKey: "address")
            newFriend.setValue(self.ageLabel.text, forKey: "age")
            newFriend.setValue(gender, forKey: "gender")

            /*let gender: String = genderSegControl.titleForSegment(at: genderSegControl.selectedSegmentIndex)!
 */


            //SAVE THE CONTEXT
            do {
                try context.save()
            }
            catch{
                print(error)
            }
         }
        else {
            print("please enter your first and last name!")
        }
    }

} //end class

friendslistViewController.swift (显示带有单元格的tableView的屏幕)

friendslistViewController.swift (screen that displays the tableView with the cells)

//
//  friendslistViewController.swift
// 
//
//  Created by on 11/10/17.
//  Copyright © 2017. All rights reserved.
//

import UIKit
import CoreData

class friendslistViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    /*
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        var DestViewController : editViewController = segue.destinationViewController as! editViewController

        DestViewController.firstNameInput = name.firstName!
    }
 */

    //outlets

    @IBOutlet weak var tableView: UITableView!

    var userArray:[Friends] = []

    override func viewDidLoad() {
        super.viewDidLoad()            

        tableView.delegate = self
        tableView.dataSource = self

        self.fetchData()
        self.tableView.reloadData()


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

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


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


    //DISPLAY LISTVIEW
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        //save first users data into array
        let name = userArray[indexPath.row]
        cell.textLabel!.text = name.firstName! + " " +
            name.lastName! + ", " +
            name.age! + ", " +
            name.gender! + ", " +
            name.address!

        return cell
    }


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

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

        if editingStyle == .delete{

            //delete a friend
            let friend = userArray[indexPath.row]
            context.delete(friend)
            (UIApplication.shared.delegate as! AppDelegate).saveContext()

            do{
                userArray = try context.fetch(Friends.fetchRequest())

            }catch{
                print(error)
            }

        }
        tableView.reloadData()

    }

    //fetch the data
    func fetchData(){
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        do{
            userArray = try context.fetch(Friends.fetchRequest())
        }
            //if error exists/catch it
        catch{
            print(error)
        }
    }

    //actions
 } //end class

editViewController.swift (用于处理编辑/保存的屏幕)

editViewController.swift (screen that handles editing/saving)

//
//  editViewController.swift
// 
//
//  Created by  on 15/10/17.
//  Copyright © 2017. All rights reserved.
//

import UIKit

import CoreData

class editViewController: UIViewController {

    @IBOutlet weak var firstName: UITextField!        
    @IBOutlet weak var lastName: UITextField!        
    @IBOutlet weak var ageLabel: UILabel!        
    @IBOutlet weak var address: UITextField!

    var firstNameInput = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        firstName.text = firstNameInput

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

 }


推荐答案

好吧,首先,您应该更改视图控制器的名称,以便它们都以大写字母开头(例如, class FriendsViewController:UIViewController ),并对文件名执行相同的操作。

Well, first you should change the names of your view controllers so they all start with capital letters (e.g. class FriendsViewController: UIViewController) and do the same with the file names.

第二,您正确地需要添加序号。您是否看过Apple文档中的 func prepare(用于segue:UIStoryboardSegue,发件人:任意?)

Secondly, you're correct about needing to add a segue. Did you take a look at func prepare(for segue: UIStoryboardSegue, sender: Any?) in Apple's documentation?

在目标视图控制器中需要一个变量( editViewController.swift ),您可以将Friend对象分配给该变量。在您的 prepare(for:sender:)方法中,您需要类似 let destinationViewController = segue.destination as的东西! EditViewController 。然后,您可以使用该 destinationViewController 变量访问目标视图控制器中的变量并将对象分配给它。

You'll need a variable in your destination view controller (editViewController.swift) that you can assign the Friend object to. In your prepare(for:sender:) method, you'll want something like let destinationViewController = segue.destination as! EditViewController. You can then use that destinationViewController variable to access variable in your destination view controller and assign the object to it.

看看你能得到多少。

这篇关于将核心数据值传递到文本字段中以进行编辑/保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆