Search code examples
swiftxcodeautolayoutuistackview

How to avoid buttons dropping off bottom of screen and prevent text view from disappearing using autolayout - xcode/swift?


I am writing a simple iOS app in swift with xcode and have a navigation view in which I have a text view (to contain a sentence or two for a question) with two buttons below to go forward and back.

I want the two buttons to fill the width of the screen with a small space between and for the text view to fill the remaining space. At the moment I've tried putting the buttons in a horizontal stack view but the buttons get squashed together. Moreover, when I then incorporate the horizontal stack (containing the buttons) then put that and the text view into a vertical stack the text cannot be seen at all when the app is run (?).

Also currently when rotating the view the buttons drop off the bottom of the screen. What is the best way of setting this to correctly display across devices/orientations using stack views and constraints? enter image description here


Solution

  • As pointed out in one of the answers you need to set set "Fill Equally" distribution type.

    After setting up the 'buttons stack view' you can either use another stack view to hold the 'buttons stack view' and 'text view',

    Or

    You can use simple constraints to setup your 'text view' along the 'buttons stack view'

    In this storyboard I have replicated both the cases.

    enter image description here

    You can always refer https://developer.apple.com/reference/uikit/uistackview. Or one of my post on other distribution types here https://stackoverflow.com/a/34059843/1790683

    UPDATE: As I see in your storyboard, your outer stack view is missing constraints. To add proper constraints, select the outer stack view and 'add new constraint' button in bottom bar. Refer screenshot

    enter image description here