Robert F Boord
Robert F Boord

Reputation: 61

Swift 2 Xcode - CGRect (moving in frame) on UIImageView

So I've got three images that I want arranged randomly. I'm using the origin of the three objects for the base point. I've tried a few different things, but they won't budge.

It's important to note that I have constraints on these images. They have a padding on top & bottom with a padding of 0 on the sides. They are also constrained to be the same size, in case constraint settings limit the movement of objects.

//the starting positions of the objects
spot_1 = img1.frame.origin
spot_2 = img2.frame.origin
spot_3 = img3.frame.origin

I've tried a few different tweaks on these sets of code:

img2.frame = CGRect(x: spot_1.x, y: spot_1.y, width: box_width, height: box_width)
img3.frame = CGRect(x: spot_2.x, y: spot_2.y, width: box_width, height: box_width)
img1.frame = CGRect(x: spot_3.x, y: spot_3.y, width: box_width, height: box_width)

&

img2.frame = spot_1
img3.frame = spot_2
img1.frame = spot_3

I've tried animating, different versions of CGrect etc. Can't get it figured out. Thank you for any help!

Upvotes: 0

Views: 555

Answers (1)

user4151918
user4151918

Reputation:

Trying to use both (Auto Layout) constraints and frames just isn't compatible. Constraints determine and set a view's frame. You shouldn't programmatically change the frame.

If you want to move a constrained object, what you would do is programmatically modify its position constraint(s).

You can programmatically change a constraint by adding an IBOutlet and connecting the Storyboard constraint to your property.

@IBOutlet weak var image1LeadingSpaceConstraint: NSLayoutConstraint!

Then in code, you can change the constraint's constant to set a new margin for your image

image1LeadingSpaceConstraint.constant = ...

You can even animate your change so the image animates to its new location

[UIView animateWithDuration:2.0 animations:^{
    [self.view layoutIfNeeded];
}];

Upvotes: 1

Related Questions