Ios 在我的ViewController类中访问函数内部的Swift字典变量时出现问题
初始化我的ViewController类,如下所示:Ios 在我的ViewController类中访问函数内部的Swift字典变量时出现问题,ios,dictionary,swift,uiviewcontroller,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
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")
}
通过这样做,该属性可用于该类的任何实例方法