Kiwo Tew
Kiwo Tew

Reputation: 1531

Is there a way to programmatically center a view from one button to another?

I wonder if I programmatically can center a view from one element to another.

The screenshot under explains it.

If I click on "Sort2" I want to animate the view from Sort2 to be centered under Sort1 instead

enter image description here

Upvotes: 1

Views: 51

Answers (2)

Candost
Candost

Reputation: 1029

There is a better way with using layout constraints. You should give center constraint between Sort2 and your view and set it's priority to High. After that give center constraint between Sort1 and your view and set it's priority to Low. After that you just need to change their priorities use this code. (In code, yourView is your whole view including these three views)

[UIView animateWithDuration:0.5 animations:^{
    [yourView layoutIfNeeded];
}];

Upvotes: 1

Shamas S
Shamas S

Reputation: 7549

In your selector for Sort2 button, add the line

[UIView animateWithDuration:1.0 animations:^{
    sort2View.center = CGPointMake(sort1View.center.x, sort1View.center.y + 50)
}];

Another much cleaner approach would be to add UIConstraints.

Upvotes: 1

Related Questions