Search code examples
swiftimageviewnslayoutconstraint

constraint together 2 imageviews to keep the same constant distance between them


My swift code below uses nslayoutconstraint to place imageviews on the view controller. I the problem is the gap the exists when the app is built on a iPad but it looks good on a iPhone. I have attached a imagine explaining the situation below. I tried linking the constraint below look where I commented but it does not work. The code below is of the 2 imageviews in question. Ben is the large imageview above them.

enter image description here

        takePhoto.topAnchor.constraint(equalTo: ben.bottomAnchor, constant : 10),
        takePhoto.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.07, constant: 0),
        takePhoto.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 50),
        takePhoto.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: 0.365,constant:  0),



        importPhot.topAnchor.constraint(equalTo: ben.bottomAnchor, constant : 10),
        importPhot.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.07, constant: 0),
        importPhot.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant : -50),
        importPhot.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: 0.365,constant:  0),
         //constraint below trying to keep a constant link between the imageviews
        importPhot.leadingAnchor.constraint(equalTo: takePhoto.trailingAnchor, constant: 5),

Solution

  • On importPhot You are mixing width anchor together with leading and trailing anchor, which doesn't make sense. You have to choose one option.

    In your case delete

    importPhot.widthAnchor.constraint(equalTo: view.widthAnchor,multiplier: 0.365,constant:  0),
    

    Now importPhot is anchored to view.trailingAnchor and takePhoto.trailingAnchor. For your use case I would recommend to anchor to the middle of the screen. For example:

    takePhoto.topAnchor.constraint(equalTo: ben.bottomAnchor, constant : 10),
    takePhoto.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.07, constant: 0),
    takePhoto.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant : 50),
    takePhoto.trailingAnchor.constraint(equalTo: view.centerXAnchor, constant :-5),
    

    and

    importPhot.topAnchor.constraint(equalTo: ben.bottomAnchor, constant : 10),
    importPhot.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.07, constant: 0),
    importPhot.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant : -50),
    importPhot.leadingAnchor.constraint(equalTo: view.centerXAnchor, constant: 5)