【问题标题】:Changing button text from modal view controller in swift快速从模态视图控制器更改按钮文本
【发布时间】:2014-07-05 21:11:21
【问题描述】:

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

一切正常,除了按钮文本没有改变。

我已经尝试设置模态视图委托 - 没有选择这样做,从原始视图控制器或模态视图控制器。

尝试调用presentingViewController - 由于某种原因总是为零。不能说别的。

尝试使用设置按钮文本的方法 - 由于按钮尚未初始化,因此出现“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)

有什么建议吗?谢谢:)

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    这对于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)
         }
    
    }
    

    希望这能给你一个大致的想法。

    【讨论】:

    • 感谢分享。但是如何传递多个值呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多