Search code examples
iosswiftxcodeuiimageview

how to declare UIImageView in my UIViewController class so that other classes can use it?


I will use GCD to run tasks that will in turn send tasks, that use wrist_band_UIImageView, to GCD main to  display.

IE.
1. ViewController starts backend task onto DispatchQueue.global which is an endless loop 
2. this endless loop periodically needs to update the UIImageView and so puts a task onto main queue to update the UIImageView.


class ViewController: UIViewController {  <<<<<<  E R R O R  Class 'ViewController' has no initializers

    @IBOutlet weak var app_title: UILabel!
    
    ////////////////////////   VARIABLES   ////////////////////////////

    var wrist_band_UIImageView: UIImageView


    override func viewDidLoad()              ///////////////////////////////////////// VIEW DID LOAD
    {
        print("viewDidLoad...")
        super.viewDidLoad()

        // Init data:
            let image = UIImage(systemName: "applewatch")      
            self.wrist_band_UIImageView = UIImageView(image: image!)

        print("viewDidLoad  starts run_app.")

        DispatchQueue.global().async{ app_class.run_app() }

        print("viewDidLoad done.")
        return   
    }
 }

UPDATE:
I changed UIImageView from static to instance, and now class line gets build error "Class 'ViewController' has no initializers".


Solution

  • I found this example that does the trick...........

    Class ViewController: UIViewController {
    
        let someImageView: UIImageView = {
           let theImageView = UIImageView()
           theImageView.image = UIImage(named: "yourImage.png")
           theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
           return theImageView
        }()
    
        override func viewDidLoad() {
           super.viewDidLoad()
    
           view.addSubview(someImageView) //This add it the view controller without constraints
           someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints
        }
    
        // do not forget the `.isActive = true` after every constraint
        func someImageViewConstraints() {
            someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
            someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
            someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
            someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
        }
    
    }