ios - 在我的 ViewController 类中访问函数内部的 Swift 字典变量时出现问题

标签 ios dictionary swift uiviewcontroller

像这样初始化我的 ViewController 类:

class ViewController: UIViewController {

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // Create a dict of images for use with the UIView menu tab
        var imageDict = [String:UIImage]()
        imageDict["hudson_terrace"] = UIImage(named: "hudson_terrace")
        imageDict["sky_room"] = UIImage(named: "sky_room")
        imageDict["rivington"] = UIImage(named: "rivington")
        imageDict["highline_ballroom"] = UIImage(named: "highline_ballroom")
        imageDict["gansevoort_park_redroom"] = UIImage(named: "gansevoort_park_redroom")
        imageDict["gansevoort_park_rooftop"] = UIImage(named: "gansevoort_park_rooftop")
        imageDict["evr"] = UIImage(named: "evr")

    }

后来在类里面写了这个函数...

    func addImageViews () {

        // loop through imageDict and add all the images as UIView subviews of menuScrollView
        for (venue_name, image) in self.imageDict {

        }
    }

我收到错误“ViewController”没有名为“imageDict”的成员。

不确定为什么 imageDict 在函数内部对我不可用。谁能建议一个更好的地方来放置 dict 以及如何访问它?

最佳答案

您将 imageDict 声明为 init 初始值设定项的本地变量,因此它仅存在于该上下文中。一旦函数(初始化程序)退出,变量就会被释放,并且不能在该上下文之外引用。

为了从类的任何方法引用它,您应该将其声明为类的属性:

class ViewController: UIViewController {
    var imageDict = [String:UIImage]()

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        // Create a dict of images for use with the UIView menu tab
        imageDict["hudson_terrace"] = UIImage(named: "hudson_terrace")
        imageDict["sky_room"] = UIImage(named: "sky_room")
        imageDict["rivington"] = UIImage(named: "rivington")
        imageDict["highline_ballroom"] = UIImage(named: "highline_ballroom")
        imageDict["gansevoort_park_redroom"] = UIImage(named: "gansevoort_park_redroom")
        imageDict["gansevoort_park_rooftop"] = UIImage(named: "gansevoort_park_rooftop")
        imageDict["evr"] = UIImage(named: "evr")
    }

通过这样做,该属性可用于该类的任何实例方法。

关于ios - 在我的 ViewController 类中访问函数内部的 Swift 字典变量时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27072496/

相关文章:

ios - 二进制字符串到人类可读字符串

ios - UITableViewCell 的详细文本标签在滚动时消失

iphone - 找不到豹中的 libxml2?

Python defaultdict(dict) 中一个键有多个值

python - 将 2 个字典与公共(public)键组合

ios - 出现新的 ViewController 时清除内存

ios - UISearchDisplayController TableView 的自定义类

java - 为什么 Map 不能使用日期作为键?

swift - 以编程方式更改 UIImageView 大小而不更改位置

Swift,对于一些 UIViews 在点击时到他们的整体 Controller