在swift中从模态视图控制器更改按钮文本

时间:2014-07-05 21:11:22

标签: ios swift

我必须按钮。每个都以模态方式打开相同的视图控制器。在那里,我有一个TableView需要返回所选的值,并设置按钮将其打开到该值。

一切正常,但按钮文字不会改变。

我尝试过设置模态视图委托 - 没有选项,从原始视图控制器或模态控制器。

尝试调用presentationViewController - 由于某种原因总是为零。不能说不然。

尝试使用设置按钮文本的方法 - 获取" 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)

任何指针?谢谢:))

1 个答案:

答案 0 :(得分: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)
     }

}

希望这能为您提供一般的想法。