How can I access to variable name and change string to it

廉价感情. 提交于 2019-12-25 04:09:36

问题


I have number of images and they are named as image0, image1, image2..., image(x).

My question is how can I access their name because I want to put all of them in array like:

@IBOutlet weak var image0: UIImageView!
@IBOutlet weak var image1: UIImageView!
@IBOutlet weak var image2: UIImageView!
@IBOutlet weak var image3: UIImageView!
@IBOutlet weak var image4: UIImageView!
@IBOutlet weak var image5: UIImageView!
...
@IBOutlet weak var image15: UIImageView!
    var counter: Int = 0
    var items :[[UIImageView]] = []
    for i in 0..<4{
        for j in 0..<4{
            items[i][j]=image(counter) //this line should be something that image0,1..x assign to the array
            counter += 1
        }
    }
}

回答1:


You can do this through the following code.

Swift 3

var items : [[UIImageView]] = []
let myMirror = Mirror(reflecting: self)
for i in 0..<4 {
    items.insert([UIImageView](), at: i)
    for j in 0..<4 {
        let propertyName = "image\(i*4 + j)"
        items[i].insert(myMirror.descendant(propertyName) as! UIImageView, at: j)
    }
}

However, this is not code that is used by devs, Look into using a UICollectionView




回答2:


I see what you are trying to do. Sadly variable names are evaluated at compile time, so that's not possible. The best thing you can do is to manually create the array.

[[image0, image1, image2], [image3, image2, image3], ...]


来源:https://stackoverflow.com/questions/40585591/how-can-i-access-to-variable-name-and-change-string-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!