2014-11-22 43 views
0

初始化我的ViewController类,像这样:问题在我的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在函数内部不可用。任何人都可以提出一个更好的地方来放置字典和如何访问它?

回答

1

您声明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") 
    } 

通过这样做,属性是提供给任何类的实例方法。