Randy Banks
Randy Banks

Reputation: 371

Resize button in swift/xcode with Autolayout enabled

I have read in several other SO posts about this topic, and it's my understanding that to resize an object when AutoLayout is enabled, you can simply change the constant properties of their constraints in your code.

I have two buttons side by side, like this

[delete][ post ]

and they take up the entire width of the screen. I want to hide the delete button for certain views, and when that happens, stretch the post button to take up the entire width of the screen. In my code, I have:

self.postButtonLeadingConstraint.constant = self.deleteButtonLeadingConstraint.constant
self.deleteButton.hidden

My delete button hides just fine, but my post button stays exactly where it is at. What is it that I am doing wrong? Any input is greatly appreciated.

EDIT: If it matters, my buttons are constrained as follows:

Delete button leading constrained to leading edge of view

Post button leading constrained to trailing edge of delete button

Delete and post button set to equal each others' widths

both buttons have their tops and buttons constrained to the view they are in, but I don't see how those could be relevant.

Upvotes: 1

Views: 861

Answers (3)

Lumialxk
Lumialxk

Reputation: 6369

Try this:

self.postButtonLeadingConstraint.constant -= self.deleteButton.frame.size.width
self.deleteButton.hidden = true

Upvotes: 1

libec
libec

Reputation: 1554

If you're targeting iOS 9 and higher then I'd suggest using UIStackView. This is super easy that way, just a matter of adding and/or removing the button from/to stack view. Here's little sample to help you understand.

Upvotes: 1

Michael
Michael

Reputation: 9044

The problem is that although you are hiding the button, it's width remains unchanged. If you use

self.deleteButtonWidthConstraint.constant = 0

Where deleteButtonWidthConstraint is an @IBOutlet hooked up to the delete button's width constraint.

Upvotes: 0

Related Questions