Robert
Robert

Reputation: 61

Programmatically Adding/Removing Images to Subview in Swift

Using code found in another post on here, I was able to programmatically draw and erase a subview, including location, width, and height, as shown in func addLoadButton and func removeSubview below. I have also figured out how to programmatically draw a picture on the main View Controller, as shown in func trailerLoadImage below. However, after many hours and attempts, I have tried to programmatically add and remove images into that subview without success.

My end goal is to be able to press three different trailer load type buttons to insert three different images (button 1 loads image 1, button 2 loads image 2, etc.) in a subview located in a specific location on the screen, and to be able to remove the images one at a time (may not be in order put on screen) by tapping on the images with a finger. The subview can be permanent or can be created and removed programmatically (as used below).

What code would I use to insert an image or multiple different images into a subview that has already been created, to remove the image(s) in the reverse order added, and to clear all images out of the subview? If this can’t be done, an acceptable alternative would be the ability to remove the image from the main VC by either tapping on it or pressing a button to clear all added images.

//Class declaration
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {

    //Boolean to include load type one in calculations
    var trailerLoad : Bool = false
    var trailerLoadDistanceFromFront = 20

    //Boolean to include load type two in calculations
    var trailerLoadTwo : Bool = false
    var trailerLoadTwoDistanceFromFront = 80

    //Boolean to include load type three in calculations
    var trailerLoadThree : Bool = false
    var trailerLoadThreeDistanceFromFront = 120

    var trailerLoadWidth : Int = 0
    var trailerLoadX : Int = 0

    //Boolean true only when subView on trailer is active
    var subViewActive : Bool = false


    override func viewDidLoad() {
        super.viewDidLoad()

        //Picker view data sources and delegates included in here and work fine
    }


    //Adds subview for loads
    @IBAction func addLoadButton(_ sender: Any) {

        let trailerLoadView: UIView = UIView(frame: CGRect(x: 252, y: 233, width: 378, height: 100))
        trailerLoadView.backgroundColor = .blue
        trailerLoadView.alpha = 0.5
        trailerLoadView.tag = 100
        trailerLoadView.isUserInteractionEnabled = true
        self.view.addSubview(trailerLoadView)

        subViewActive = true
    }


    //If subViewActive is true, calls alert to get distance load type one is from front, moves on to insert and position image, changes trailerLoad bool to true
    @IBAction func trailerLoadOneButton(_ sender: Any) {
        //If subViewActive is true:
            //Calls alert to get distance load type one is from front, puts in var trailerLoadDistanceFromFront
            //Calls trailerLoadImage() to insert and position load type one image
            //Changes bool trailerLoad to true
        //If subViewActive is false:
            //Calls alert to tell user that they need to click Add Load button (create subview) before adding load types one, two, or three
    }


    //Add trailer load type one image, scales and positions it relatively accurately in view.
    //To be duplicated and modified for load types two and three in the future, with different images (trailerLoadTypeTwoPic and trailerLoadTypeThreePic)
    func trailerLoadImage() {

        trailerLoadWidth = 378 * 60 / trailerTotalLength
        trailerLoadX = 378 * trailerLoadDistanceFromFront / trailerTotalLength

        let imageView = UIImageView(frame: CGRect(x: (252 + trailerLoadX), y: (333 - trailerLoadWidth), width: trailerLoadWidth, height: trailerLoadWidth));
        let image = UIImage(named: “trailerLoadTypeOnePic”);

        imageView.image = image;
        self.view.addSubview(imageView)
    }


    //Calls func removeSubview to remove subview
    @IBAction func resetButton(_ sender: Any) {

        removeSubview()
    }


    //Removes subview for loads
    @objc func removeSubview(){

        subViewActive = false

        if let viewWithTag = self.view.viewWithTag(100) {
            viewWithTag.removeFromSuperview()
        }else{
            print("No!")
        }
    }
}

Thank you very much to anybody that offers assistance or advice.

Upvotes: 3

Views: 2468

Answers (1)

Robert Dresler
Robert Dresler

Reputation: 11150

Don't use tags! Just create variables in global scope for your views

var imageViews = [UIImageView]()

then when you need to add them first append them to your array and then add them to view

imageViews.append(imageView)
view.addSubview(imageView)

Then when you need to remove your all views from their superview, use method removeFromSuperview() for each view in array

imageViews.forEach { $0.removeFromSuperview() }
imageViews.removeAll()

or if you need to remove just one view at specific index

imageViews[index].removeFromSuperview()
imageViews.remove(at: index)

Upvotes: 2

Related Questions