swift - 将图像保存为与核心数据字符串的一对一关系
问题描述
我下面的代码应遵循下图。它具有一个表格视图,用于存储用户生成的字符串。使用核心数据实体 Item 属性 tbox。Then when the selects a tableview cell it segues the string into another class which features a label and imageview. 用户应该能够从照片库中选择一张照片,然后将其保存到核心数据 Entity Pic 属性 pic。每当用户从 tableview 单元格中选择一个名称时,当且仅当图像保存在其中时,它应该始终与 table view 单元格中的名称匹配。这是 GitHub 的链接https://github.com/redrock34/tableviewcell-relationship-between-text-and-string/blob/master/michaelVick.xcodeproj.zip。
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)")
}
}
}