【问题标题】:Declaring a global variable in swift while using UITableView使用 UITableView 时快速声明全局变量
【发布时间】:2016-08-16 02:11:40
【问题描述】:

我对如何在我的 swift 项目中的函数之外声明全局变量感到困惑。 这是我用来将 UITableView 的选定行的文本保存为变量“chosenFeed”的代码: 1

然后,我尝试使用此变量在另一个视图控制器上打开 URL,例如: 2

我知道我做错了,因为“chosenFeed”是该覆盖函数的本地。 所以,我不知道如何声明这个全局变量以供不同的 VC 访问。有人推荐了structs,所以我在tableView VC中试了一下:

struct GlobalVariable {
    static var indexPath = tableView.indexPathForSelectedRow
    static var currentCell = tableView.cellForRowAtIndexPath(indexPath!)! as UITableViewCell
    static var choosenFeed = tableDict[currentCell.textLabel!.text!]
}

但这在太多模棱两可的引用中也不起作用。有什么解决办法吗?

【问题讨论】:

  • 不要使用全局变量。在第二个视图控制器上声明一个属性,然后在呈现之前设置该属性。你在使用故事板吗?如果是这样,那么您可以在prepareForSegueWithIdentifier: 中执行此操作
  • 是的,就像@Paulw11 提到的那样,不要使用全局变量。如果你的项目太大,你会被太多的变量名弄糊涂,不利于开发。您的变量将仅在这 2 个不同的视图控制器之间使用吗?

标签: ios swift xcode uitableview global-variables


【解决方案1】:

正如其他海报提到的那样,使用全局变量并不是最好的主意。这不是一种好的编码实践,一旦你的应用程序扩展,它就会变得非常混乱。在 TableView 和另一个 View(ViewController、Cell 等)之间传递信息时,您有两种选择(不包括使用全局变量)。

第一个选项:使用 prepareForSegue

在您的目标 ViewController 上,您需要创建一个名为 selectedFeed 的变量。然后在 TableView 的底部,您可以使用这个 prepareForSegue 函数来传递数据:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if let destinationVC = segue.destinationViewController as ViewController {
       destinationVC.chosenFeed = self.chosenFeed
   }
}

或者你可以使用 didSelectRowAtIndexPath

如果需要发送此数据并且基于选择的单元格,您可以使用 didSelectRowAtIndexPath。您仍然需要在目标 ViewController 上添加一个名为 selectedFeed 的变量。如果您选择此选项,您还需要在 Storyboard 中命名您的 segue。

 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

   // Youll need the name of your ViewController here to pass the variable
   let destinationVC = "nameOfTheDestination_VC()"
   destinationVC.chosenFeed = self.chosenFeed

   //This is where you use the named segue from the Storyboard
   destinationVC.performSegueWithIdentifier("segueName", sender: self)

}

这些建议中的任何一个都应该是您正在寻找的。如果毕竟,您仍然决定需要一个全局变量(毕竟这是所问的问题),您只需要在类声明上方声明变量:

var chosenFeed : String? 
class About_VC: UIViewController {
   //code here 
}

最后一点,从您发布的示例图片中,请注意强制展开。干杯!

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    相关资源
    最近更新 更多