委托方法向前传递数据

时间:2016-05-22 11:04:58

标签: swift delegates uitextview

我使用委托方法成功地在两个视图控制器之间传回数据。

第一个视图控制器是"评论"屏幕,第二个是"编辑"屏幕主要包含UITextView。

当我在编辑屏幕上更改文本视图的内容并点击保存时,它成功传递到审阅屏幕。但是当我返回编辑屏幕时,UITextView为空。

如何确保编辑屏幕保留代理中存储的值?

感谢您抽出宝贵时间来了解一下。

查看视图控制器

class AddCampaignViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate, TitleViewDelegate {

    @IBOutlet var titleSubtitle: UILabel!

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "AddTitleViewController" {

            let addTitleViewController = segue.destinationViewController as! AddTitleViewController

             addTitleViewController.delegate = self

         }

    }

    override func viewDidLoad() {

        super.viewDidLoad()

    }


    func setCampaignTitle(campaignTitle: String) {

        titleSubtitle.text = campaignTitle

    }

}

编辑视图控制器

protocol TitleViewDelegate {

    func setCampaignTitle(campaignTitle: String)

}

class AddTitleViewController: UIViewController, UITextViewDelegate {

    var delegate : TitleViewDelegate!

    var campaignTitle : String!

    @IBOutlet var titleTextView: UITextView!

    override func viewDidLoad() {

        super.viewDidLoad()

        titleTextView.becomeFirstResponder()

        let logButton : UIBarButtonItem = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: self, action: "saveTitle:")

        self.navigationItem.rightBarButtonItem = logButton

    }

    func saveTitle(sender: UIBarButtonItem) {

            delegate.setCampaignTitle(titleTextView.text!)

            self.navigationController?.popViewControllerAnimated(true)

    }

}

1 个答案:

答案 0 :(得分:3)

segue每次都会创建一个新的EditViewController。要向前传递数据,您需要将数据分配给EditViewController属性,然后将该数据复制到titleTextView.text方法中的viewDidLoad。这是必要的,因为@IBOutlet未设置,nil运行时仍为prepareForSegue

所以:

  1. 将属性var textToEdit = ""添加到您的EditViewController
  2. prepareForSegue中,设置addTitleViewController.textToEdit = /* the text you want to edit */
  3. viewDidLoad的{​​{1}}中,设置EditViewController
  4. 注意:您的titleTextView.text = textToEdit应声明delegate以避免保留周期(这会导致您永远不会释放weak来泄漏内存。您的EditViewController应该也可以声明为@IBOutlet