How to change position of a programmatically added image view by tapping? (image view not manually added to the Main.storyboard)

Viewed 826

Here is the code that is just about adding an image view programmatically:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let imageName = "thisIsAnImage.png"
        let image = UIImage(named: imageName)
        let imageView = UIImageView(image: image!)
        view.addSubview(imageView)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // change position of image
    }

}

That is how I know how to add an image view programmatically now.

I could change the position by writing code inside the viewDidLoad-function, but this function only runs at the beginning of running the app.

How to write the code (that is for adding the image view) outside the viewDidLoad-function in order to access the image and change the position by tapping?

2 Answers

You should store a reference to the created image view, so you can move it in the touches routine. Example:

class ViewController: UIViewController {

var imageView : UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    let imageName = "image.png"
    let image = UIImage(named: imageName)
    imageView = UIImageView(image: image!)
    view.addSubview(imageView)

    imageView.frame.origin = CGPoint(x: 100, y: 100)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touchpt = touches.first?.location(in: self.view) {
        imageView.frame.origin = touchpt
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touchpt = touches.first?.location(in: self.view) {
        imageView.frame.origin = touchpt
    }

}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touchpt = touches.first?.location(in: self.view) {
        imageView.frame.origin = touchpt
    }

}

}

You should make your image view a class level variable, like so:

import UIKit

class ViewController: UIViewController {

    var imageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let imageName = "thisIsAnImage.png"
        let image = UIImage(named: imageName)
        imageView = UIImageView(image: image!)
        view.addSubview(imageView)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        imageView.frame = // provide a CGRect of your choice
    }

}
Related