Search code examples
stringuiimageview

name from UIImageView from String


how can I replace the name of a UIImageview with a string

name\(number).isHidden = false

is not working

name1.isHidden = false

thanks Jürgen


Solution

  • You cannot do that. Swift is a compiled language, not a scripted language.

    "name1" exists only in your source code.

    If you really have a need to work with objects (whether image views or other UI elements) to where you can refer to them "by name," your best bet would be to create a dictionary.

    Assuming you have added your image views in Storyboard and connected them via @IBOutlet such as:

    @IBOutlet var name1: UIImageView!
    @IBOutlet var name2: UIImageView!
    @IBOutlet var name3: UIImageView!
    @IBOutlet var name4: UIImageView!
    

    You can create a dictionary in viewDidLoad() like this:

    class TestViewController: UIViewController {
        
        @IBOutlet var name1: UIImageView!
        @IBOutlet var name2: UIImageView!
        @IBOutlet var name3: UIImageView!
        @IBOutlet var name4: UIImageView!
    
        var imageViews: [String : UIImageView] = [:]
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            imageViews["name1"] = name1
            imageViews["name2"] = name2
            imageViews["name3"] = name3
            imageViews["name4"] = name4
        }
    }
    

    Then later you can get a reference to your image view "by name":

        let i = 3
        // make sure we get a valid reference
        if let imgView = imageViews["name\(i)"] {
            imgView.isHidden = false
        }
        
    

    This is not a great approach, for many reasons.

    One better way is to connect them to an @IBOutlet Collection:

    @IBOutlet var imageViews: [UIImageView]!
    

    Connect all of your image views to that @IBOutlet ... then at run-time you can get a reference as easily as:

    imageViews[number].isHidden = false