gpt4 book ai didi

ios - 如何使用警报文本字段在 swift ios 中保存多个数据

转载 作者:行者123 更新时间:2023-11-30 11:37:50 25 4
gpt4 key购买 nike

如何从用户界面警报文本字段中保存多个数据,我已经可以使用这行代码将一个数据保存到数据库中。正如您所注意到的,只有一个文本字段,我添加了 2 个文本字段来保存地址、日期等其他数据,但当我保存数据时,仅保存了名称。代码部分是 Add New Chore 。保存它的函数位于 func saveItemInLocalDB(groceryItem : Item) 上,您可以在下面找到它。

let alert = UIAlertController(title: "Add New Chore", message: "", preferredStyle:
UIAlertControllerStyle.alert)

alert.addTextField(configurationHandler: textFieldHandler)

导入UIKit 导入核心数据

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;
}
}


}

最佳答案

根据我的理解,您正在尝试添加多个具有相同字段的数据。

所以我想你可以使用我的保存数据的方法

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)
}

在警报中添加文本字段的代码:

    //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)

关于ios - 如何使用警报文本字段在 swift ios 中保存多个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49548485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com