[swift]使用 NSUserDefaults 从 UITextView 气泡框保存击键

标签: UITextView ios Swift
发布时间: 2016/1/28 20:55:23
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有气泡框命名为 NotesViewController ,包含 UITextView 。气泡框发生当用户点击 Notes 按钮 GraphViewController

气泡框显示正常,但在文字 UITextField 消失当我单击关闭气泡框,我想将无法保存它。

如何将文本保存后每一次击键或当用户单击从气泡框的示例还将作为一个答案!!

这里是我的有:

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

解决方法 1:

罗瑞的评论是正确的。将 NotesViewController 设置为允许我使用跟踪更改的方法的委托。

这是我的解决方案:

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

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
        }
    }
}
官方微信
官方QQ群
31647020