Search code examples
iosswiftuiimageviewposition

IOS Cant Reposition UIImageView at runtime


I have looked at other questions on SO regarding this issue and my code seems to follow the provided solutions so I don't know Where I am going wrong. I ma trying to reset the position of an image view when the screen loads. the size will depend on the a base image.

The image always remains where it was placed in interface builder. There are no constraints on the image view.

Does it matter where i call this From? i have tried viewDidLoad() , viewWillLoad() And viewDidAppear()

Code

@IBOutlet weak var cameraPreview: UIView!
@IBOutlet weak var glassesOverlay: UIImageView!

    print("Before")
    print("overlay x: \(glassesOverlay.frame.origin.x)")
    print("overlay y: \(glassesOverlay.frame.origin.y)")
    print("overlay W: \(glassesOverlay.frame.width)")
    print("overlay H: \(glassesOverlay.frame.height)")


    let glassesOrigin = CGPointMake( (cameraPreview.frame.width / 2) - (glassesOverlay.frame.width / 2), cameraPreview.frame.height / 3)

    //let glassesOrigin = CGPointMake( 179.0, 179.0)
    let glassesWidth = cameraPreview.frame.width / 2.0
    let glassesSize = CGSizeMake(glassesWidth, glassesWidth / 4)

    //        glassesOverlay.frame.origin =  CGPointMake( (cameraPreview.frame.width / 2) - (glassesOverlay.frame.width / 2), cameraPreview.frame.height / 3)
    //        glassesOverlay.frame.size = glassesSize

    glassesOverlay.frame = CGRect(origin: glassesOrigin, size: glassesSize)

    //cameraPreview.subviews[0].frame = CGRect(origin: glassesOrigin, size: glassesSize)
    glassesOverlay.layer.borderColor = UIColor.purpleColor().CGColor
    glassesOverlay.layer.borderWidth = 2.0

    cameraPreview.layer.borderColor = UIColor.purpleColor().CGColor
    cameraPreview.layer.borderWidth = 2.0
    print("After")
    print("overlay x: \(glassesOverlay.frame.origin.x)")
    print("overlay y: \(glassesOverlay.frame.origin.y)")
    print("overlay W: \(glassesOverlay.frame.width)")
    print("overlay H: \(glassesOverlay.frame.height)")

as you can see i have tried explicitly setting values with the same result. i am printing the position and dimensions before and after and they print the changed values.

Print Output

Before
overlay x: 135.0
overlay y: 382.0
overlay W: 320.0
overlay H: 128.0
After
overlay x: 224.0
overlay y: 296.667
overlay W: 384.0
overlay H: 96.0

But it remains unmoved.


Solution

  • Are you using auto layout? Then modify the constraints instead of manipulating the frame directly. After modifying the constraints, you need to

    view.setNeedsLayout()
    view.layoutIfNeeded()
    

    If you are not using auto layout, this should work, except the old frame is matching the new frame or the outlet is holding another view than you expect.

    Edit:

    Please have a look at how autolayout works. There are good WWDC videos explaining it as well.