2016-05-22 144 views
1

我正在使用委託方法成功地在兩個視圖控制器之間傳回數據。委託方法傳遞數據轉發

第一個視圖控制器是一個「審查」屏幕,第二個是主要包含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) 

    } 

} 

回答

3

的賽格瑞將創建一個新的EditViewController每次。要向前傳遞數據,您需要將數據分配給EditViewController屬性,然後將該數據複製到viewDidLoad方法中的titleTextView.text。這是必要的,因爲@IBOutlet s沒有設置,並且當prepareForSegue運行時仍然是nil

所以:

  1. 財產var textToEdit = ""添加到您的EditViewController
  2. prepareForSegue,設置addTitleViewController.textToEdit = /* the text you want to edit */
  3. EditViewControllerviewDidLoad,設置titleTextView.text = textToEdit

注意:您delegate應被宣佈weak避免保留週期(這將導致您從未釋放EditViewController s到內存泄露你的@IBOutlet S的關係也被宣佈weak