Swift 使用核心数据字符串将图像保存为一对一关系

Swift 使用核心数据字符串将图像保存为一对一关系,swift,uitableview,core-data,segue,one-to-one,Swift,Uitableview,Core Data,Segue,One To One,我下面的代码应该遵循下图。它具有一个tableview,其中存储用户生成的字符串。使用核心数据实体项属性tbox。然后,当选择一个tableview单元格时,它将字符串分为另一个类,该类具有标签和imageview。用户应该能够从照片库中选择一张照片,然后保存到核心数据实体Pic attriubte Pic。当且仅当图像保存在tableview单元格中时,用户从tableview单元格中选择名称的任何时候都应始终与tableview单元格中的名称匹配。这是GitHub的链接 导入UIKit;导

我下面的代码应该遵循下图。它具有一个tableview,其中存储用户生成的字符串。使用核心数据实体项属性tbox。然后,当选择一个tableview单元格时,它将字符串分为另一个类,该类具有标签和imageview。用户应该能够从照片库中选择一张照片,然后保存到核心数据实体Pic attriubte Pic。当且仅当图像保存在tableview单元格中时,用户从tableview单元格中选择名称的任何时候都应始终与tableview单元格中的名称匹配。这是GitHub的链接

导入UIKit;导入CoreData
类ViewController:UIViewController、UITableViewDelegate、UITableViewDataSource{
func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
返回itemName.count
}
变量项名称:[NSManagedObject]=[]
var txtField=UITextField()
var btn=ui按钮()
var theField=UITableView()
重写func viewDidLoad(){
super.viewDidLoad()
//加载视图后执行任何其他设置。
[txtField,btn,theField].forEach({
self.view.addSubview($0)
})
txtField.frame=CGRect(x:view.center.x-100,y:view.center.y-250,宽度:200,高度:40)
txtField.placeholder=“输入名称”
txtField.textAlignment=.center
txtField.borderStyle=UITextField.borderStyle.roundedRect
btn.frame=CGRect(x:view.center.x-100,y:view.center.y-200,宽度:200,高度:40)
theField.frame=CGRect(x:view.center.x-100,y:view.center.y-150,宽度:200,高度:250)
btn.backgroundColor=UIColor.red
btn.setTitle(“添加名称”,用于:。正常)
btn.addTarget(self,action:#选择器(save),for:.touchUpInside)
view.backgroundColor=UIColor.systemGreen
theField.dataSource=self
theField.delegate=self
loadData()
寄存器(UITableViewCell.self,强制重用标识符:“MyCell”)
}
@objc func save(){
将appDeldeaget=UIApplication.shared.delegate设为!AppDelegate
让context=AppDeldeGet.persistentContainer.viewContext
让entity=NSEntityDescription.entity(名为“Item”,在:context中)
让title=NSManagedObject(实体:entity!,插入到:context)
title.setValue(txtField.text,forKey:“tbox”)
做{
尝试context.save()
itemName.append(标题)
}
抓住{
打印(“d”)
}
txtField.text=“”
self.theField.reloadData()
}
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
让title=itemName[indexPath.row]
让cell=field.dequeueReusableCell(标识符为:“MyCell”,表示:indexPath)
cell.selectionStyle=.default
将attr1=title.value(forKey:“name”)设为?字符串
让text=[attr1].flatMap{$0}.reduce(“,+)
cell.textlab?.text=“\(text)”
单元格.textLabel?.textAlignment=.center
cell.layoutMargins=UIEdgeInsets.zero
cell.preservesPerViewLayoutMargins=false
cell.separatorInset=UIEdgeInsets.zero
cell.layoutMargins=UIEdgeInsets.zero
返回单元
}
func loadData(){
让appDelegate=UIApplication.shared.delegate作为?appDelegate else{return}
让managedContext=appDelegate.persistentContainer.viewContext
let fetch=NSFetchRequest(entityName:“tbox”)
做{
self.itemName=尝试managedContext.fetch(fetch)
}
抓住{
打印(“无法加载。\(错误)”)
}
}
func tableView(tableView:UITableView,didSelectRowAt indexPath:indexPath){
取消选择行(at:indexPath,动画:true)
让cell=theField.cellForRow(at:indexPath)
设vc=fullScreen()
vc.tim=(单元格?.textlab!.text)!
vc.modalPresentationStyle=.overCurrentContext//实际上,全屏显示会更好
self.present(vc,动画:true)
}
func tableView(tableView:UITableView,commit editingStyle:UITableViewCell.editingStyle,forRowAt indexath:indexPath){
如果editingStyle==UITableViewCell.editingStyle.delete{
将appd=UIApplication.shared.delegate设为!AppDelegate
让context=appd.persistentContainer.viewContext
context.delete(itemName[indexPath.row])
itemName.remove(位于:indexPath.row)
做{
尝试context.save()
}
抓住{
打印(“d”)
}
self.theField.reloadData()
}
}
}
全屏类:UIViewController、UIImagePickerControllerDelegate、UINavigationControllerDelegate{
var imagePicker:UIImagePickerController!
@objc func图像(image:UIImage,didFinishSavingWithError:error?,contextInfo:UnsafeRawPointer){
如果let error=error{
//我们发现一个错误!
让ac=UIAlertController(标题:“保存错误”,消息:error.localizedDescription,preferredStyle:.alert)
ac.addAction(UIAlertAction(标题:“确定”,样式:。默认值))
当前(ac,动画:真)
}否则{
让ac=UIAlertController(标题:“已保存!”,消息:“您更改的图像已保存到照片中。”,首选样式:。警报)
ac.addAction(UIAlertAction(标题:“确定”,样式:。默认值))
当前(ac,动画:真)
}
}
func imagePickerController(picker:UIImagePickerController,didFinishPickingMediaWithInfo:[UIImagePickerController.InfoKey:Any]){
//信息字典可能包含图像的多个表示形式。您希望使用原始图像。
让guard选择图像=inf
import UIKit;import CoreData

 class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return itemName.count
    }



    var itemName : [NSManagedObject] = []
    var txtField = UITextField()
    var btn = UIButton()
    var theField = UITableView()

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

        [txtField,btn,theField].forEach({
            self.view.addSubview($0)
        })
        txtField.frame = CGRect(x: view.center.x-100, y: view.center.y-250, width: 200, height: 40)
        txtField.placeholder = "Enter Name"
        txtField.textAlignment = .center
        txtField.borderStyle = UITextField.BorderStyle.roundedRect
        btn.frame = CGRect(x: view.center.x-100, y: view.center.y-200, width: 200, height: 40)
        theField.frame = CGRect(x: view.center.x-100, y: view.center.y-150, width: 200, height: 250)
        btn.backgroundColor = UIColor.red
        btn.setTitle("Add Name", for: .normal)
        btn.addTarget(self, action: #selector(save), for: .touchUpInside)
        view.backgroundColor = UIColor.systemGreen
        theField.dataSource = self
        theField.delegate = self
        loadData()
        theField.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
    }

    @objc func save() {
        let appDeldeaget = UIApplication.shared.delegate as! AppDelegate
        let context = appDeldeaget.persistentContainer.viewContext


        let entity = NSEntityDescription.entity(forEntityName: "Item", in: context)


        let theTitle = NSManagedObject(entity: entity!, insertInto: context)

        theTitle.setValue(txtField.text, forKey: "tbox")



        do {
            try context.save()
            itemName.append(theTitle)

        }
        catch {
            print("d")
        }
        txtField.text = ""
        self.theField.reloadData()

    }




    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let title = itemName[indexPath.row]
        let cell = theField.dequeueReusableCell(withIdentifier: "MyCell", for : indexPath)

        cell.selectionStyle = .default
        let attr1 = title.value(forKey: "name") as? String



        let text = [attr1].flatMap { $0 }.reduce("", +)
        cell.textLabel?.text = "\(text)"

        cell.textLabel?.textAlignment = .center

        cell.layoutMargins = UIEdgeInsets.zero




        cell.preservesSuperviewLayoutMargins = false
        cell.separatorInset = UIEdgeInsets.zero
        cell.layoutMargins = UIEdgeInsets.zero



        return cell

    }

    func loadData() {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let managedContext = appDelegate.persistentContainer.viewContext
        let fetch = NSFetchRequest<Item>(entityName: "tbox")
        do {
            self.itemName = try managedContext.fetch(fetch)
        }
        catch {
            print("Could not load. \(error)")
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        let cell = theField.cellForRow(at: indexPath)

        let vc = fullScreen()
        vc.tim = (cell?.textLabel!.text)!

        vc.modalPresentationStyle = .overCurrentContext // actually .fullScreen would be better
        self.present(vc, animated: true)

    }



    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {


        if editingStyle == UITableViewCell.EditingStyle.delete {
            let appd = UIApplication.shared.delegate as! AppDelegate
            let context = appd.persistentContainer.viewContext

            context.delete(itemName[indexPath.row])
            itemName.remove(at: indexPath.row)

            do {
                try context.save()
            }
            catch {
                print("d")
            }
            self.theField.reloadData()

        }
    }




}




    class fullScreen : UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate{



        var imagePicker: UIImagePickerController!

        @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
            if let error = error {
                // we got back an error!
                let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "OK", style: .default))
                present(ac, animated: true)
            } else {
                let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "OK", style: .default))
                present(ac, animated: true)
            }
        }


        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

            // The info dictionary may contain multiple representations of the image. You want to use the original.
            guard let selectedImage = info[.originalImage] as? UIImage else {
                fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
            }

            // Set photoImageView to display the selected image.

            txt.image = selectedImage

            // Dismiss the picker.
            dismiss(animated: true, completion: nil)
        }

    var tim = ""
    var cook = UILabel()
            var add = UIButton()
    var back = UIButton()
    var txt = UIImageView()
    var itemName : [NSManagedObject] = []
    var itemName2 : [NSManagedObject] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.systemTeal

        [cook,back,txt,add].forEach({
            $0.translatesAutoresizingMaskIntoConstraints = false
            self.view.addSubview($0)
        })
        back.backgroundColor = UIColor.systemRed
        txt.backgroundColor = UIColor.systemGray
        cook.text = tim
        cook.frame = CGRect(x: view.center.x-115, y: view.center.y-200, width: 60, height: 30)
        back.frame = CGRect(x: view.center.x-115, y: view.center.y-100, width: 30, height: 30)
         add.frame = CGRect(x: view.center.x+115, y: view.center.y-100, width: 30, height: 30)
        txt.frame = CGRect(x: view.center.x-115, y: view.center.y-0, width: 100, height: 50)
        back.addTarget(self, action: #selector(moveRight), for: .touchUpInside)
          add.addTarget(self, action: #selector(ad), for: .touchUpInside)
        loadData()

    }


    @objc func moveRight() {

        save()

        let vc = ViewController()

        vc.modalPresentationStyle = .overCurrentContext

        self.present(vc, animated: true)

            }
        @objc func ad() {

     imagePicker =  UIImagePickerController()
           imagePicker.delegate = self
           imagePicker.sourceType = .photoLibrary
           present(imagePicker, animated: true, completion: nil)

                }

    @objc func save() {
        let appDeldeaget = UIApplication.shared.delegate as! AppDelegate
        let context = appDeldeaget.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Item", in: context)
        let theTitle = NSManagedObject(entity: entity!, insertInto: context)
        theTitle.setValue(txt.image, forKey: "tbox")



        do {
            try context.save()
            itemName.append(theTitle)

        }catch{}





    }

    func loadData() {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
        let managedContext = appDelegate.persistentContainer.viewContext
        let fetch = NSFetchRequest<Item>(entityName: "tbox")
        do {
            self.itemName2 = try managedContext.fetch(fetch)


        }
        catch {
            print("Could not load. \(error)")
        }
    }


    }