Search code examples
xcodeautolayoutconstraints

Adding constraints to buttons


How can one add constraints to buttons without interfering with the other setting(button color, visibility and activeness). I've added constraints to both buttons (see image). The white button turns to the color of the background and is not tappable(Not able to press in simulator) and the purple button vanishes completely.

enter image description here


Solution

    1. Your button without background is ok, you will not see the tap in simulator. Connect an IBOutlet and set some action for it, you'll see that it works.
    2. Purple button has worn constraints. You set up fixed top and bottom constraints for it according to iPhone7 screen. However you are running SE simulator. SE has smaller screen than 7 and auto layout engine cannot apply your constraints properly so it brake some of the constraints (you can see related messages in log). E.G. You've set that purple button must have 400 points to top of the screen (or a control above) and 237 points to the bottom of the screen. Button in storyboard have height = 30. Then we have 400+237+30=667. 667 it's iPhone 6,7 screen height so everything is ok. When you run your app on SE, what is happening: SE has screen height 568. So autolayout engine try to set 400 to the top - ok. 237 to the bottom? error. There is only 168 points left to the bottom. So I'll brake bottom constraint, inform you in the log that it was happen, and set maximum possible value so 168. In the result we have 568 - 400 - 168 = 0 - that is button's height. Try to understand how auto layout engine build the UI and update your constraints properly.

    If you want your purple button to be placed in the middle between bottom and first button I'd suggest: 1. add an empty view and stretch it to fit all the empty space between 1st button and bottom. Make it transparent by setting background color to clear color. 2. add constraints to it 0-0-0-0 all sides 0 to nearest view. 3. put your purple button inside this view and place in the middle (you'll see blue cross lines when it will be in the middle) 4. add only 2 constraints to purple button: center horizontally in container and center vertically in container.

    That will solve your issue.