I have a popover named NotesViewController
which contains a UITextView
. The popover happens when a user clicks on the Notes
button in the GraphViewController
.
The popover appears fine but the text in the UITextField
disappears whenever I click off the popover and I want to be able to save it.
Examples of how to save the text either after each keystroke or when the user clicks off of the popover would also work as an answer!!
Here is what I have:
class NotesViewController: UIViewController
{
@IBOutlet weak var noteView: UITextView! {
didSet{
defaults.setObject(noteView.text, forKey: "previousText")
noteView.text = notes
}
}
var notes = " " {
didSet {
noteView?.text = notes
}
}
let defaults = NSUserDefaults.standardUserDefaults()
class GraphViewController: UIViewController, GraphViewDataSource, UIPopoverPresentationControllerDelegate
{
//
//...
// prepare segue for popover
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
//this is the identifier for the popover segue
case "Show Notes":
if let nvc = segue.destinationViewController as? NotesViewController {
if let ppc = nvc.popoverPresentationController {
ppc.delegate = self
}
if let previousNotes = nvc.defaults.stringForKey("previousText") {
nvc.notes = previousNotes
}
}
default: break
}
}
}
}
Rory's comment was correct. Setting the NotesViewController as the delegate allowed me to use methods which track changes.
This is the solution I had:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//first check if this is the segue we are talking about here
if let identifier = segue.identifier {
switch identifier {
case "Show Notes":
if let nvc = segue.destinationViewController as? NotesViewController {
if let ppc = nvc.popoverPresentationController {
ppc.delegate = self
}
if let previousNotes = nvc.defaults.stringForKey("textPreviouslyEnteredByUser") {
nvc.notes = previousNotes
}
}
default: break
}
}
}
and
class NotesViewController: UIViewController, UITextViewDelegate
{
var defaults = NSUserDefaults.standardUserDefaults()
@IBOutlet weak var noteView: UITextView! {
didSet {
noteView?.text = notes
}
}
override func viewDidLoad() {
super.viewDidLoad()
noteView.delegate = self
}
func textViewDidChange(textView: UITextView) {
defaults.setObject(textView.text, forKey: "textPreviouslyEnteredByUser")
}
var notes = " " {
didSet {
noteView?.text = notes
}
}
}