Iam Wayne
Iam Wayne

Reputation: 561

Append Array with UserDefaults input text

I have an Array of strings which is populating a collection view and that works well. The issue is I want to append that array with Strings that is saved in user defaults from user input textfield. I am getting the UserDefault data, The issue is it is not showing up in seperate collection view cell. it is getting attached at the end of each string in the current cells. Thanks in advance, any help would be appreciated.

This is what I tried so far:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell

    let defaults = UserDefaults.standard
    let value = defaults.string(forKey: "Gratitude")
    print(value!)
    //Array that I am trying to append with userdefault data       
    gratitudeArray.append(value!)

    // Configure the cell
    cell.cellLabel.text = gratitudeArray[indexPath.row]
    return cell
}

// I am geeting user input from alert and saving in userdefaults like this:

func presentAlert() { let alertController = UIAlertController(title: "", message: "Create your own Gratitude:", preferredStyle: .alert)

    let confirmAction = UIAlertAction(title: "Save", style: .default) { (_) in
        if let field = alertController.textFields?[0] {
            // store data
            UserDefaults.standard.set(field.text, forKey: "Gratitude")
            UserDefaults.standard.synchronize()
        } else {
            print()
        }
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

    alertController.addTextField { (textField) in
        //print(textField.text!)
        //textField.placeholder = ""
    }

    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

    self.present(alertController, animated: true, completion: nil)
}

Upvotes: 1

Views: 1045

Answers (3)

Iam Wayne
Iam Wayne

Reputation: 561

I solved the issue by creating an array in my alert controller to hold user input and then save that array to user defaults.

func presentAlert() { let alertController = UIAlertController(title: "", message: "Create your own Gratitude:", preferredStyle: .alert)

    let confirmAction = UIAlertAction(title: "Save", style: .default) { (_) in
        if let field = alertController.textFields {

            let textFieldArray = field as [UITextField]
            let text = textFieldArray[0].text

            let key = "Gratitude"

            var myArray = UserDefaults.standard.array(forKey: key) ?? []
            myArray.append(String(describing: text!))
            UserDefaults.standard.set(myArray, forKey: key)

            print(myArray)


        } else {
            print()
        }
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

    alertController.addTextField { (textField) in

    }

    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

    self.present(alertController, animated: true, completion: nil)
}

Upvotes: 0

Vaibhav Misra
Vaibhav Misra

Reputation: 471

If I understand your problem correctly, you want number of cells to increase by one (the value you extract out of UserDefaults). For that, you should append it some place which is outside collection view's data source methods (like viewDidLoad()) and then reload your collection view.

override func viewDidLoad() {
    super.viewDidLoad()

    let defaults = UserDefaults.standard
    strValue = defaults.string(forKey: "Gratitude")
    gratitudeArray.append(strValue)
    self.collectionView.reloadData()
}

Upvotes: 1

Jay Patel
Jay Patel

Reputation: 2740

Store String in ViewDidLoad() like below:

var strValue: String = ""

override func viewDidLoad() {
    super.viewDidLoad()

    let defaults = UserDefaults.standard
    strValue= defaults.string(forKey: "Gratitude")
}

and display in cellForItemAt like this:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    cell.cellLabel.text = gratitudeArray[indexPath.row] + " " + strValue
    return cell
}

Upvotes: 1

Related Questions