【问题标题】:Swift save text to an instance/global variable when UIButton is pressed按下 UIButton 时,Swift 将文本保存到实例/全局变量
【发布时间】:2016-11-08 17:22:37
【问题描述】:

所以我有一个 UItextfield 和一个 UIButton 我想知道在实例变量中按下按钮后是否有一种方法可以保存文本,以便我可以在我的其他类中使用它。 我想做的事情是让用户在屏幕 1 的文本字段中输入一些文本,然后当用户点击按钮时,我想将他带到屏幕 2 但是在该屏幕 2 的类中我想知道什么文本用户输入以便相应地显示数据。 现在我只有一个按钮的操作函数,我访问其中的文本并将其保存到实例变量中,但是当我在另一个类中调用它时它是空的,因为我将它初始化为空。所以有人可以帮助我并告诉我如何去做。 谢谢!

这是第一个屏幕的代码

 var searchRecipe = ""
 @IBAction func SearchButton(sender: UIButton) {
    if let recipe = RecipeSearchBar.text {
        searchRecipe = recipe
    }
}

这是第二个屏幕的代码。我已经在这个屏幕的第一个屏幕上连接了按钮,所以当用户点击按钮时,他会到达这里。

  var recipeName:[String] = []
  var imageURL:[String] = []
  var timeInSeconds:[Float] = []
  func apiCall()
    {
        //search recipe API call
        var searchRecipe = ""
        searchRecipe = RecipesViewController().searchRecipe
        print (searchRecipe) //prints nothing
        endpoint = "http://api.yummly.com/v1/api/recipes?_app_id=apiId&_app_key=apiKey&q=\(searchRecipe)" //this is where I want to use the searchRecipe text from class 1
}

【问题讨论】:

  • 请展示一些代码,向我们展示您是如何创建和展示您的第二个视图的。此外,这个问题已经有很多答案了,所以你可能会发现你的答案已经被关闭,除非它得到很大改进。

标签: swift uibutton uitextfield


【解决方案1】:

我个人会做以下事情(根据我对您问题的解释):

请注意,我认为您正在实施基于视图控制器的导航是理所当然的,并且您知道什么是 IBOutlets、IBActions 和 Segues

  1. 在第一个视图控制器中创建一个 IBOutlet 属性 UITextField 命名为RecipeSearchBar 并将其连接到相关文本 字段。
  2. 在第二个视图控制器中创建一个变量value 类型 字符串;
  3. 将故事板转场标识符更改为“toSecondViewController
  4. 然后在第一个视图控制器中创建要调用的 IBAction 当 UIButton 被按下时。

在你的情况下:

@IBAction func SearchButton(sender: UIButton) {
    if let recipe = RecipeSearchBar.text {
        searchRecipe = recipe
    }

    //If you are navigating into a new view view controller
    //here you need to call self.presentViewController(...)

}

在此操作中,您将调用self.presentViewController 显示你的第二个视图控制器,但你必须做最后一个 非常重要的一步:将 UITextField 的值传递给实例 它将容纳第二个视图控制器

要实现这一点,请在您的第一个视图控制器中覆盖 prepareForSegue 并共享 UITextField 值。一旦您调用 self.presentViewController 以进一步实现,就会触发此方法。

//Did not tested the code but should just be ok
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

       if (segue.identifier == "toSecondViewController")
        {
            //Create the instance
            let secondViewController = segue.destinationViewController
            //Set the value
            secondViewController.value = searchRecipe;
        }
    }

您现在可以出发了。 希望这会有所帮助,如果是这样,请为其他人标记问题。 再见

【讨论】:

  • 非常感谢,这正是我想做的,您的解决方案效果很好。感谢您的帮助!
  • 很高兴它有帮助,享受你的编码:)
猜你喜欢
  • 1970-01-01
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多