2014-07-05 27 views
0

我必須按鈕。每個人模態地打開相同的視圖控制器。在那裏,我有一個TableView需要返回選定的值,並設置按鈕打開它的值。在swift中更改模態視圖控制器中的按鈕文本

一切正常,除了按鈕文字沒有改變。

我已經嘗試設置模態視圖委託 - 沒有選擇這樣做,從原始視圖控制器或模態之一。

嘗試調用presentsViewController - 出於某種原因始終爲零。否則無法說出來。

嘗試使用設置按鈕文本的方法 - 獲取「Optional.none」錯誤,因爲按鈕尚未初始化。

嘗試設置變量並使viewDidAppear方法更改文本 - 當視圖返回到視圖中時,變量保持不變。

代碼呈現模式的看法:

@IBAction func getFromStation(sender : AnyObject) { 
    let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
    let vc : informationViewController = storyboard.instantiateViewControllerWithIdentifier("informationViewController") as informationViewController 
    vc.parent = "RoutePlannerFrom" 
    self.presentModalViewController(vc, animated: true) 
} 

代碼試圖返回選定的值:

let vc : RoutePlannerViewController = storyboard.instantiateViewControllerWithIdentifier("routePlannerViewController") as RoutePlannerViewController 
     vc.btnFrom.setTitle(stopNames[indexPath.row] as String, forState: UIControlState.Normal) 
     self.dismissModalViewControllerAnimated(true) 

任何指針?謝謝:)

回答

4

這聽起來像是爲delegation pattern

在良好的問題InformationViewController你可以定義一個新的委託協議:

protocol InformationDelegate { 
    func didSelectValue(value: String) 
} 

class InformationViewController { 
    var delegate: InformationDelegate? // The delegate that the parent view controller will conform to 
    ... 

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { 
     // Get the value and call the delegate method 
     if let d = self.delegate { 
     d.didSelectValue(valueForButton) // Get the value from your datasource and return it to the parent through the delegate method. 
     } 
    } 
} 

在父視圖控制器你將要順應這個代表協議:

class ParentViewController: UIViewController, InformationDelegate { 
    @IBOutlet var btnFrom: UIButton 
    .... 

    func didSelectValue(value: String) { 
     self.btnFrom.setTitle(value) 
    } 


    @IBAction func getFromStation(sender : AnyObject) { 
     let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
     let vc : informationViewController = storyboard.instantiateViewControllerWithIdentifier("informationViewController") as informationViewController 
     vc.parent = "RoutePlannerFrom" 
     vc.delegate = self // Set up this class as the InformationsViewControllers delegate 
     self.presentModalViewController(vc, animated: true) 
    } 

} 

希望這給你的一般想法。

相關問題