如何从ui alert文本字段保存多个数据,我已经可以使用这行代码将一个数据保存到数据库中。正如你注意到只有一个文本字段我添加了2个文本字段用于保存其他数据,如地址,日期,但当我保存数据时,只保存了名称。代码的一部分是Add New Chore。保存它的功能在func saveItemInLocalDB(groceryItem:Item)上,你可以在下面找到它。
let alert = UIAlertController(title: "Add New Chore", message: "", preferredStyle:
UIAlertControllerStyle.alert)
alert.addTextField(configurationHandler: textFieldHandler)
导入UIKit 导入CoreData
class GroceryViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UISearchBarDelegate, NSFetchedResultsControllerDelegate, GroceryItemCollectionViewCellDelegate {
@IBOutlet var collectionView: UICollectionView!
@IBOutlet weak var seeTask: UIButton!
@IBOutlet weak var see: UIButton!
@IBOutlet var searchBar: UISearchBar!
let unselectedCellColor : UIColor = UIColor(red: 60/255, green: 78/255, blue: 127/255, alpha: 1.0)
let selectedCellColor : UIColor = UIColor(red: 93/255, green: 173/255, blue: 195/255, alpha: 1.0)
var searchBarActive : Bool?
var textToSearch : String?
var loggedInUserHouseNumber : String?
var loggedInUsername : String?
open var context: NSManagedObjectContext!
var fetchedResultsController: NSFetchedResultsController<GroceryItem>!
let datePicker = UIDatePicker()
let reuseIdentifier = "Cell"
@IBAction func checkListButtonIsPressed(_ sender: Any) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let cartVC = storyBoard.instantiateViewController(withIdentifier: "GroceryCheckListViewController") as! GroceryCheckListViewController
self.navigationController?.pushViewController(cartVC, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
loggedInUserHouseNumber = (UserDefaults.standard.value(forKey: "loggedInUserHouseNumber") as! String)
loggedInUsername = (UserDefaults.standard.value(forKey: "loggedInUsername") as! String)
// likeLabel.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_2 * 3))
var a = loggedInUsername
if ((a?.lowercased().range(of: "mother")) != nil) {
seeTask.setTitle("Completed Tasks", for: .normal)
print("true")
} else {
print("false")
seeTask.setTitle("View Details",for: .normal)
// self.collectionView.isd = true
}
searchBarActive = false
textToSearch = nil
self.navigationItem.title = "Chore List"
self.navigationController?.navigationBar.isHidden = false
self.searchBar.delegate = self
self.setUpCollectionView()
// Do any additional setup after loading the view.
}
func createDatePicker() {
}
func setUpCollectionView() {
configureFetchedResultsController()
do {
try fetchedResultsController.performFetch()
} catch {
print("An error occurred")
}
self.collectionView.reloadData()
}
func configureFetchedResultsController() {
self.fetchedResultsController = nil
let itemsFetchRequest = NSFetchRequest<GroceryItem>(entityName: "GroceryItem")
let primarySortDescriptor = NSSortDescriptor(key: "name", ascending: true)
// let secondarySortDescriptor = NSSortDescriptor(key: "commonName", ascending: true)
if (textToSearch != nil) {
itemsFetchRequest.predicate = NSPredicate(format: "name contains[c] %@ AND houseNo == %@",textToSearch!, loggedInUserHouseNumber!)
} else {
itemsFetchRequest.predicate = NSPredicate(format: "houseNo == %@",loggedInUserHouseNumber!)
}
itemsFetchRequest.sortDescriptors = [primarySortDescriptor]
self.context = getContext()
self.fetchedResultsController = NSFetchedResultsController<GroceryItem>(
fetchRequest: itemsFetchRequest,
managedObjectContext: getContext(),
sectionNameKeyPath: nil,
cacheName: nil)
self.fetchedResultsController.delegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if self.searchBarActive! {
if let sections = fetchedResultsController.sections {
let currentSection = sections[section]
return currentSection.numberOfObjects
}
return 0
} else {
if let sections = fetchedResultsController.sections {
let currentSection = sections[section]
return (currentSection.numberOfObjects + 1)
}
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if self.searchBarActive! {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! GroceryItemCollectionViewCell
cell.buttonDelegate = self
let item = fetchedResultsController.object(at: indexPath)
cell.label.text = item.name
cell.deleteButton.tag = indexPath.row
if item.isSelected {
cell.backgroundColor = selectedCellColor
} else {
cell.backgroundColor = unselectedCellColor
}
return cell
} else {
if indexPath.row == 0 {
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddNewCell", for: indexPath as IndexPath) as! AddNewCollectionViewCell
cell.backgroundColor = unselectedCellColor // make cell more visible in our example project
return cell
} else {
let index = IndexPath(row: (indexPath.row - 1), section: 0)
let item = fetchedResultsController.object(at: index)
// get a reference to our storyboard cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! GroceryItemCollectionViewCell
cell.buttonDelegate = self
cell.deleteButton.tag = indexPath.row - 1
cell.label.text = item.name
if item.isSelected {
cell.backgroundColor = selectedCellColor
} else {
cell.backgroundColor = unselectedCellColor
}
return cell
}
}
}
func buttonTapped(cell: GroceryItemCollectionViewCell) {
let index = IndexPath(row: (cell.deleteButton.tag), section: 0)
self.context.delete(fetchedResultsController.object(at: index))
self.setUpCollectionView()
}
func textFieldHandler(textField: UITextField!)
{
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
label.text = "Text"
textField.placeholder = "Enter Chore Name"
if (textField) != nil {
print("true")
}
}
func textFieldHandler1(textField: UITextField!)
{
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
label.text = "Text"
textField.placeholder = "Enter Date"
if (textField) != nil {
print("true")
}
}
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
func saveItemInLocalDB(groceryItem : Item) {
let context = getContext()
//retrieve the entity that we just created
let entity = NSEntityDescription.entity(forEntityName: "GroceryItem", in: context)
let item = NSManagedObject(entity: entity!, insertInto: context)
//set the entity values
item.setValue(groceryItem.name, forKey: "name")
item.setValue(false, forKey: "isSelected")
item.setValue(loggedInUserHouseNumber, forKey: "houseNo")
//save the object
do {
try context.save()
print("ang item:", groceryItem.name)
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
let cell = collectionView.cellForItem(at: indexPath)
if self.searchBarActive! {
let index = IndexPath(row: indexPath.row, section: 0)
let item = fetchedResultsController.object(at: index)
if item.isSelected {
item.isSelected = false
cell?.backgroundColor = unselectedCellColor
} else {
item.isSelected = true
cell?.backgroundColor = selectedCellColor
}
do {
try context.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
} else {
if indexPath.row == 0 {
let alert = UIAlertController(title: "Add New Chore", message: "", preferredStyle:
UIAlertControllerStyle.alert)
alert.addTextField(configurationHandler: textFieldHandler)
alert.addTextField(configurationHandler: textFieldHandler1)
// alert.addTextField(configurationHandler: { (textField) in
// textField.placeholder = "Enter Chore Name"
// })
let a = loggedInUsername
if ((a?.lowercased().range(of: "mother")) != nil) {
print("true")
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
let newItem : String = (alert.textFields?.first?.text)!
if !newItem.isEmpty {
let item = Item(name: newItem)
// let item2 = Item(name: newItem2)
self.saveItemInLocalDB(groceryItem: item!)
self.setUpCollectionView()
}
}))
self.present(alert, animated: true, completion:nil)
} else {
let alertVC : UIAlertController = UIAlertController(title: "No Access", message: "please try again", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Close", style: .default, handler: nil))
self.present(alertVC, animated: true, completion: nil)
print("false")
}
} else {
let index = IndexPath(row: (indexPath.row - 1), section: 0)
let item = fetchedResultsController.object(at: index)
if item.isSelected {
item.isSelected = false
cell?.backgroundColor = unselectedCellColor
} else {
item.isSelected = true
cell?.backgroundColor = selectedCellColor
}
do {
try context.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
}
}
// This method updates filteredData based on the text in the Search Box
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if (searchBar.text?.isEmpty)!{
searchBarActive = false
textToSearch = nil
} else {
searchBarActive = true
textToSearch = searchText
}
self.setUpCollectionView()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.searchBarActive = false
textToSearch = nil
self.searchBar.text = ""
self.view.endEditing(true)
self.setUpCollectionView()
// self.collectionView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.searchBarActive = true
textToSearch = searchBar.text
self.view.endEditing(true)
self.setUpCollectionView()
// self.collectionView.reloadData()
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.searchBar.setShowsCancelButton(false, animated: true)
self.searchBarActive = false
textToSearch = nil
self.setUpCollectionView()
// self.collectionView.reloadData()
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.searchBar.setShowsCancelButton(true, animated: true)
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
break;
case .update:
break;
case .move:
break;
case .delete:
break;
}
}
}
答案 0 :(得分:0)
根据我的理解,您正尝试使用相同的字段添加多个数据。
所以我想你可以使用我保存数据的方法
func saveDataInCoreData(nameOfGroccery:String){
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let groceryData = GroceryItem(context: context) // Link GroceryItem & Context
groceryData.name = nameOfGroccery
groceryData.isSelected = false
groceryData.houseNo = loggedInUserHouseNumber
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
这将一次保存所有数据。
在评论中提及您的问题
您可以尝试以下逻辑
步骤:1 在顶部创建变量
var strName:String = String()
步骤:2 修改您的代码,如下所示
strName = (alert.textFields?.first?.text)!
if strName != ""{
self.saveDataInCoreData(nameOfGroccery: strName)
}
在警报中添加TextField的代码:
//1. Create the alert controller.
let alert = UIAlertController(title: "Add New Chore", message: "", preferredStyle: .alert)
//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
textField.text = "Some default text"
}
// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
if textField?.text != ""{
print("Text field: \(textField?.text!)")
self.saveDataInCoreData(nameOfGroccery: textField?.text)
}
}))
// 4. Present the alert.
self.present(alert, animated: true, completion: nil)