Caspar B
Caspar B

Reputation: 539

Instance member cannot be used on type when adding UIImage Programatically

I'm new to Swift, and I'm still trying to get my head around many things. I made a class for a Meteorite:

class Meteorite {
        var width: Int,
            height: Int,
            x: Int,
            y : Int

        init(width: Int, height: Int, x: Int, y: Int) {
            self.width = width
            self.height = height
            self.x = x
            self.y = y

            let image = UIImage(named: "square")
            let imageView = UIImageView(image: image!)
            imageView.frame = CGRect(x: self.x, y: self.y, width: self.width, height: self.height)
            view.addSubview(imageView)
        }
    }

... And I'm trying to make the meteors appear through UIImage View elements. However, on the line: view.addSubview(imageView)

I keep getting thrown the error:

Instance member 'view' cannot be used on type 'ViewController'

I might be doing this wrong, but this class is defined within the ViewController class, which is a subclass of UIViewController. I can't find anything that makes much sense to my situation online. Help is greatly appreciated :)

Upvotes: 0

Views: 694

Answers (1)

Jacob King
Jacob King

Reputation: 6157

Meteorite may be nested within a UIViewController subclass, but you are still referencing a view property within the context of the Meteorite class. Essentially, you are sending a message to a variable that doesn't exist.

The thing to do here is to move any manipulation of the view hierarchy outside of the init for an element. This should be handled by the view controller, not the subview.

I would suggest configuring the Meteorite object in it's init, but adding it to the view controller's view within, say the viewDidLoad: method of the view controller.

Upvotes: 0

Related Questions