Post not yet marked as solved
Ive setup a tableview controller and am using it for a weight tracking list w/ coredata to save all of the entries made. While everything works as far as adding entries and displaying them while the app is open, it's not displaying those entries on the next app load. So either my save or load method is not doing its job. I appreciate the help as im relatively new to swift coding.import UIKit
import CoreData
class TodoViewController: UITableViewController {
var items = [Items]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var selectedCategory: Items?{
didSet{
loadItems()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: Table View Datasource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Item", for: indexPath)
let item = items[indexPath.row]
cell.textLabel?.text = item.name
cell.accessoryType = item.completed ? .checkmark : .none
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
items[indexPath.row].completed = !items[indexPath.row].completed
saveItems()
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete){
let item = items[indexPath.row]
items.remove(at: indexPath.row)
context.delete(item)
do{
try context.save()
}catch{
print("Error deleting item with \(error)")
}
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Weight", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Save", style: .default) { (action) in
let newItem = Items(context: self.context)
newItem.name = textField.text!
self.items.append(newItem)
self.saveItems()
}
alert.addAction(action)
alert.addTextField { (field) in
textField = field
textField.placeholder = "Add Weight"
}
present(alert, animated: true, completion: nil)
}
func saveItems(){
do{
try context.save()
}catch{
print("Error Saving item with \(error)")
}
self.tableView.reloadData()
}
func loadItems(){
let request: NSFetchRequest = Items.fetchRequest()
do{
items = try context.fetch(request)
}catch{
print("Error fetching data from context \(error)")
}
tableView.reloadData()
}
}
I've developed an iOS app with a button, segment control and a uiimageview. In the assets folder, there are 26 pictures, named card1 to card26. If I use the below code, it displays each of the 26 images in a random order. How would I flip that code to show each picture in order of image name, card1...card2...etc? I've searched for the last hour and cant find exactly what I'm looking for. I appreciate the help.let Number = Int.random(in: 2...26) imageView.image = UIImage(named: "card\(Number)")
Post not yet marked as solved
I currently have an app that logs your weight using a tableview and coredata, which is 100% working! I'm attempting to add a datepicker in the UIAlertAction and save it using CoreData as well as display it as a subtitle in my tableview. I have already added it to the datamodel entity but how do i add it to the alertaction and then save it as the tableview subtitle? Below is my current working code:class seventhViewController: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var itemName: [NSManagedObject] = []
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest(entityName: "Title")
do
{
itemName = try context.fetch(fetchRequest)
}
catch
{
print("Error loading data")
}
}
var titleTextField: UITextField!
func titleTextField(textfield: UITextField){
titleTextField = textfield
titleTextField.placeholder = "enter weight here"
}
@IBAction func addButton(_ sender: Any) {
let alert = UIAlertController(title: "Add Weight", message: "", preferredStyle: .alert)
let addAction = UIAlertAction(title: "Save", style: .default, handler: self.save)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(addAction)
alert.addAction(cancelAction)
alert.addTextField(configurationHandler: titleTextField)
self.present(alert, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
context.delete(itemName[indexPath.row])
itemName.remove(at: indexPath.row)
do
{
try context.save()
}
catch
{
print("There was an error in deleting.")
}
}
self.tableView.reloadData()
}
func save(alert: UIAlertAction!) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Title", in: context)!
let theTitle = NSManagedObject(entity: entity, insertInto: context)
theTitle.setValue(titleTextField.text, forKey: "title")
do
{
try context.save()
itemName.append(theTitle)
}
catch
{
print("There was an error in saving.")
}
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let title = itemName[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = title.value(forKey: "title") as? String
cell.textLabel?.textColor = UIColor.white
return cell
}
}
Post not yet marked as solved
I have 2 viewcontrollers, one displays the UI and the 2nd are settings. Im using the below code to save a segmented control button:UserDefaults.standard.set(selectorLabel.selectedSegmentIndex, forKey: "stateSelected")I then call it by:if let value = UserDefaults.standard.value(forKey: "stateSelected"){
let selectedIndex = value as! Int
selectorLabel.selectedSegmentIndex = selectedIndex
}This works as intended.How would i save the actual title of each button press? For instance the one side of the control is labeled "LBs & INs" and the other "KGs & CMs". I want to save which one is selected. I then want to be able to use that saved text value on a label on the first viewcontroller when the view loads
Post not yet marked as solved
I have an app I developed where I’m using two pickerview box’s using the tag property: one for gender and one for a list of items. Once I choose either pickerview, it somehow increments the other pickerview to an entry with an actual value and doesn’t start from the empty entry I created at [0]. I make my first selection and when I go into the 2nd list it’s already sitting on 50-55 (first entry with a value and sits at [1]. If i dont move from [1] to another and then back to [1] the label is still blank. - If i click off of pre-selected item and go back to it, all works fine. Pasting the pickerview code below - let me know if more info is needed and thanks in advance!Added a video as to exactly what is happening:https://www.youtube.com/watch?v=JnHii-c1E3M&feature=youtu.be let gendOption = ["", "Male","Female"] //first array for first textfield
let actOption = ["", "50%-55%", "55%-60%", "60%-65%", "65%-70%", "70%-75%", "75%-80%", "80%-85%", "85%-90%", "90%-95%"] //array for 2nd textfield
let pickerView = UIPickerView()
var currentTxtFldTag : Int = 10
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
//return priorityTypes.count
if currentTxtFldTag == 10
{
return gendOption.count
}
else
{
return actOption.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
//return priorityTypes[row]
if currentTxtFldTag == 10
{
return gendOption[row]
}
else
{
return actOption[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//selectedPriority = priorityTypes[row]
//activityTextBox.text = selectedPriority
if currentTxtFldTag == 10
{
genderSelection.text = gendOption[row]
}
else
{
activityTextBox.text = actOption[row]
}
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField.tag == 10 // *** OPTION
{
currentTxtFldTag = 10
}
else // activity OPTION
{
currentTxtFldTag = 20
}
pickerView.reloadAllComponents()
return true
}
func createPickerView() {
let pickerView = UIPickerView()
pickerView.delegate = self
activityTextBox.inputView = pickerView
}