0
votes

Maybe somebody can help me with a problem I am tackling with InterfaceBuilder and Auto Layout.

I have a containerView (yellow) in which I have a view controller which has a view that is filled with a StackView (blue). This StackView is pinned to the top, left, right with = 0 and pinned to the bottom with >= 0.

Then within the StackView need to have a ScrollView (orange) (vertical scrolling) where I add Subviews during runtime (between 1 and 20 labels). This ScrollView should take up all the remaining Space of the view and have a minimum hight of 100px.

When I run the application though, the ScrollView is not scrollable. and also the content of the first part of the stack view is pushed out of the view (at the top).

I have the Scrollview set to Content Compression Resistance Priority to 1000. No change.

I am lost, how I can fix this and any help/guidance is much appreciated.

Here some layouts, how all should look:

ScrollView filled

ScrollView partially filled

Small Device

1
What about the spacing between the yellow and blue views? How is it determined? - André Slotta
i have a View Controller with a NavigationBar, inside this Vc is the yellow ViewContainer. 10px to NavBar, and the sides. Inside is the StackView (blue) pinned at 0px to the superview. So the yellow space is actually a bit misleading, i used it to show the hierarchy. - Maverick2805
Would it be better to separate the ScrollView outside of the Stack view? stack View at the Top, ScrollView at the bottom with the StackView therein? That maybe works as a workaround, but it'd be mich interested in what I am doing wrong. I feel I am too stupid for AutoLayout. - Maverick2805
Obviously you want to horizontally "inset" the scrollview from the rest of the stack view's content. So it would be better to not put it into the stack view. - André Slotta
Okay, thanks, I thought that should be a possibility. So basically if I wanted Labels | ScrollView | Labels, then I'd need StackView | ScrollView | StackView? Thanks for the help, much appreciated. - Maverick2805

1 Answers

1
votes

Here is one way to lay out your views...

enter image description here

Note that the "Dynamic Content" label is a subview of the scrollView, but is not in the stackView... I'm assuming from your images that it would be a "title" of some sort. Its constraints are used to define the top / leading / trailing and width of the scrollView's contentSize. The "Dyna Stack" view will determine the height / bottom.

Result after adding a few labels:

And after adding enough labels for scrolling:

Here is the source of the Storyboard (to make it easier to see all the layout elements):

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15400" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
    <device id="retina4_7" orientation="portrait" appearance="light"/>
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15404"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="tne-QT-ifu">
            <objects>
                <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="Maverick" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <stackView opaque="NO" contentMode="scaleToFill" distribution="fillEqually" spacing="20" translatesAutoresizingMaskIntoConstraints="NO" id="117-6U-FYG">
                                <rect key="frame" x="40" y="40" width="295" height="30"/>
                                <subviews>
                                    <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Vf7-GC-TmS">
                                        <rect key="frame" x="0.0" y="0.0" width="137.5" height="30"/>
                                        <color key="backgroundColor" systemColor="systemBlueColor" red="0.0" green="0.47843137250000001" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                        <state key="normal" title="Add">
                                            <color key="titleColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                        </state>
                                        <connections>
                                            <action selector="addTapped:" destination="BYZ-38-t0r" eventType="touchUpInside" id="guo-Zq-b1a"/>
                                        </connections>
                                    </button>
                                    <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="3Kz-xL-gyr">
                                        <rect key="frame" x="157.5" y="0.0" width="137.5" height="30"/>
                                        <color key="backgroundColor" systemColor="systemBlueColor" red="0.0" green="0.47843137250000001" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                        <state key="normal" title="Remove">
                                            <color key="titleColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                        </state>
                                        <connections>
                                            <action selector="removeTapped:" destination="BYZ-38-t0r" eventType="touchUpInside" id="xv6-bC-c5X"/>
                                        </connections>
                                    </button>
                                </subviews>
                            </stackView>
                            <containerView opaque="NO" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="jv2-F6-WcO">
                                <rect key="frame" x="20" y="110" width="335" height="517"/>
                                <connections>
                                    <segue destination="BU8-S1-sGS" kind="embed" id="pLu-Bb-fDK"/>
                                </connections>
                            </containerView>
                        </subviews>
                        <color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
                        <constraints>
                            <constraint firstItem="117-6U-FYG" firstAttribute="leading" secondItem="6Tk-OE-BBY" secondAttribute="leading" constant="40" id="3D7-vE-QG7"/>
                            <constraint firstItem="6Tk-OE-BBY" firstAttribute="trailing" secondItem="117-6U-FYG" secondAttribute="trailing" constant="40" id="CK8-KW-Pm2"/>
                            <constraint firstItem="6Tk-OE-BBY" firstAttribute="bottom" secondItem="jv2-F6-WcO" secondAttribute="bottom" constant="40" id="E2H-NW-tUx"/>
                            <constraint firstItem="117-6U-FYG" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="JnT-dj-EtL"/>
                            <constraint firstItem="6Tk-OE-BBY" firstAttribute="trailing" secondItem="jv2-F6-WcO" secondAttribute="trailing" constant="20" id="V70-Qo-9Ea"/>
                            <constraint firstItem="117-6U-FYG" firstAttribute="top" secondItem="6Tk-OE-BBY" secondAttribute="top" constant="40" id="VGK-Ol-Vqv"/>
                            <constraint firstItem="jv2-F6-WcO" firstAttribute="leading" secondItem="6Tk-OE-BBY" secondAttribute="leading" constant="20" id="py5-VV-PzD"/>
                            <constraint firstItem="jv2-F6-WcO" firstAttribute="top" secondItem="117-6U-FYG" secondAttribute="bottom" constant="40" id="ul2-Rp-xdk"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-718" y="90"/>
        </scene>
        <!--Sub View Controller-->
        <scene sceneID="ofE-9O-3Zb">
            <objects>
                <viewController id="BU8-S1-sGS" customClass="SubViewController" customModule="Maverick" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="ZSF-IV-JZX">
                        <rect key="frame" x="0.0" y="0.0" width="335" height="517"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="eDt-4V-gxm" userLabel="Just to Show Stack Frame">
                                <rect key="frame" x="32" y="16" width="271" height="485"/>
                                <color key="backgroundColor" red="0.45138680930000002" green="0.99309605359999997" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                            </view>
                            <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="31" translatesAutoresizingMaskIntoConstraints="NO" id="QEf-Fd-Vyo">
                                <rect key="frame" x="36" y="20" width="263" height="477"/>
                                <subviews>
                                    <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="24" translatesAutoresizingMaskIntoConstraints="NO" id="V9q-T5-bad">
                                        <rect key="frame" x="0.0" y="0.0" width="263" height="138"/>
                                        <subviews>
                                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="BPT-QG-EeY">
                                                <rect key="frame" x="0.0" y="0.0" width="263" height="20.5"/>
                                                <color key="backgroundColor" red="0.99336069822311401" green="0.89430927864019549" blue="0.94426094444331177" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                <nil key="textColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                            <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="8" translatesAutoresizingMaskIntoConstraints="NO" id="VLQ-n9-nfD">
                                                <rect key="frame" x="0.0" y="44.5" width="263" height="49"/>
                                                <subviews>
                                                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label 1" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Npr-AI-qHW">
                                                        <rect key="frame" x="0.0" y="0.0" width="263" height="20.5"/>
                                                        <color key="backgroundColor" red="0.99336069822311401" green="0.89430927864019549" blue="0.94426094444331177" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
                                                        <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                        <nil key="textColor"/>
                                                        <nil key="highlightedColor"/>
                                                    </label>
                                                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label 2" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Hfl-Ub-zjq">
                                                        <rect key="frame" x="0.0" y="28.5" width="263" height="20.5"/>
                                                        <color key="backgroundColor" red="0.99336069822311401" green="0.89430927864019549" blue="0.94426094444331177" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
                                                        <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                        <nil key="textColor"/>
                                                        <nil key="highlightedColor"/>
                                                    </label>
                                                </subviews>
                                            </stackView>
                                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label 3" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="NpO-cr-hPg">
                                                <rect key="frame" x="0.0" y="117.5" width="263" height="20.5"/>
                                                <color key="backgroundColor" red="0.99336069822311401" green="0.89430927864019549" blue="0.94426094444331177" alpha="1" colorSpace="custom" customColorSpace="displayP3"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                <nil key="textColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                        </subviews>
                                    </stackView>
                                    <scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="LuK-Bh-b6R">
                                        <rect key="frame" x="0.0" y="169" width="263" height="308"/>
                                        <subviews>
                                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Dynamic Content" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="33O-PE-pv7">
                                                <rect key="frame" x="8" y="8" width="247" height="20.5"/>
                                                <color key="backgroundColor" red="0.45009386540000001" green="0.98132258650000004" blue="0.4743030667" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                <nil key="textColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                            <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="8" translatesAutoresizingMaskIntoConstraints="NO" id="eH7-Hu-tJN">
                                                <rect key="frame" x="8" y="48.5" width="247" height="77.5"/>
                                                <subviews>
                                                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Layout design labels" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="G4E-pX-zmu">
                                                        <rect key="frame" x="0.0" y="0.0" width="247" height="20.5"/>
                                                        <color key="backgroundColor" red="0.45009386540000001" green="0.98132258650000004" blue="0.4743030667" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                        <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                        <nil key="textColor"/>
                                                        <nil key="highlightedColor"/>
                                                    </label>
                                                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Removed in viewDidLoad()" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="bzC-dL-w38">
                                                        <rect key="frame" x="0.0" y="28.5" width="247" height="20.5"/>
                                                        <color key="backgroundColor" red="0.45009386540000001" green="0.98132258650000004" blue="0.4743030667" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                        <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                        <nil key="textColor"/>
                                                        <nil key="highlightedColor"/>
                                                    </label>
                                                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Sub-Label 3" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="vzO-vG-JOF">
                                                        <rect key="frame" x="0.0" y="57" width="247" height="20.5"/>
                                                        <color key="backgroundColor" red="0.45009386540000001" green="0.98132258650000004" blue="0.4743030667" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                        <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                        <nil key="textColor"/>
                                                        <nil key="highlightedColor"/>
                                                    </label>
                                                </subviews>
                                            </stackView>
                                        </subviews>
                                        <color key="backgroundColor" systemColor="systemYellowColor" red="1" green="0.80000000000000004" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                        <constraints>
                                            <constraint firstItem="eH7-Hu-tJN" firstAttribute="centerX" secondItem="33O-PE-pv7" secondAttribute="centerX" id="CCi-45-C2R"/>
                                            <constraint firstItem="eH7-Hu-tJN" firstAttribute="top" secondItem="33O-PE-pv7" secondAttribute="bottom" constant="20" id="HWf-Pp-eJo"/>
                                            <constraint firstItem="33O-PE-pv7" firstAttribute="top" secondItem="Z4n-lt-83b" secondAttribute="top" constant="8" id="QGO-EC-a1N"/>
                                            <constraint firstItem="33O-PE-pv7" firstAttribute="trailing" secondItem="Z4n-lt-83b" secondAttribute="trailing" constant="8" id="fz4-KU-6BP"/>
                                            <constraint firstItem="Z4n-lt-83b" firstAttribute="bottom" secondItem="eH7-Hu-tJN" secondAttribute="bottom" constant="8" id="lkW-Mv-xeJ"/>
                                            <constraint firstItem="33O-PE-pv7" firstAttribute="width" secondItem="KFx-Yf-vSh" secondAttribute="width" constant="-16" id="loG-jL-d0d"/>
                                            <constraint firstItem="33O-PE-pv7" firstAttribute="leading" secondItem="Z4n-lt-83b" secondAttribute="leading" constant="8" id="qxx-0L-bkh"/>
                                            <constraint firstItem="eH7-Hu-tJN" firstAttribute="width" secondItem="33O-PE-pv7" secondAttribute="width" id="tKW-fj-A10"/>
                                        </constraints>
                                        <viewLayoutGuide key="contentLayoutGuide" id="Z4n-lt-83b"/>
                                        <viewLayoutGuide key="frameLayoutGuide" id="KFx-Yf-vSh"/>
                                    </scrollView>
                                </subviews>
                            </stackView>
                        </subviews>
                        <color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="eDt-4V-gxm" firstAttribute="height" secondItem="QEf-Fd-Vyo" secondAttribute="height" constant="8" id="3Br-Qe-Txd"/>
                            <constraint firstAttribute="trailingMargin" secondItem="QEf-Fd-Vyo" secondAttribute="trailing" constant="20" id="4pW-Bm-Akv"/>
                            <constraint firstItem="QEf-Fd-Vyo" firstAttribute="leading" secondItem="ZSF-IV-JZX" secondAttribute="leadingMargin" constant="20" id="CMn-y9-bUf"/>
                            <constraint firstItem="eDt-4V-gxm" firstAttribute="centerY" secondItem="QEf-Fd-Vyo" secondAttribute="centerY" id="D3l-c7-3Hc"/>
                            <constraint firstItem="eDt-4V-gxm" firstAttribute="centerX" secondItem="QEf-Fd-Vyo" secondAttribute="centerX" id="Ntf-HA-sIt"/>
                            <constraint firstItem="eDt-4V-gxm" firstAttribute="width" secondItem="QEf-Fd-Vyo" secondAttribute="width" constant="8" id="W6S-Fg-hru"/>
                            <constraint firstItem="QEf-Fd-Vyo" firstAttribute="top" secondItem="ZSF-IV-JZX" secondAttribute="topMargin" constant="20" id="cXx-bE-SaR"/>
                            <constraint firstAttribute="bottomMargin" secondItem="QEf-Fd-Vyo" secondAttribute="bottom" constant="20" id="tOm-gp-iUg"/>
                        </constraints>
                    </view>
                    <connections>
                        <outlet property="dynaStack" destination="eH7-Hu-tJN" id="6WL-HO-RQF"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="EQR-GS-QRJ" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-20" y="90"/>
        </scene>
    </scenes>
</document>

And the code used for this example:

//
//  ViewController.swift
//
//  Created by Don Mag on 11/13/19.
//

import UIKit

class ViewController: UIViewController {

    var subVC: SubViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func addTapped(_ sender: Any) {
        subVC?.addLabel()
    }

    @IBAction func removeTapped(_ sender: Any) {
        subVC?.removeLabel()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? SubViewController {
            subVC = vc
        }
    }

}

class SubViewController: UIViewController {

    @IBOutlet weak var dynaStack: UIStackView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // remove design-time labels
        dynaStack.arrangedSubviews.forEach {
            $0.removeFromSuperview()
        }

    }

    func addLabel() -> Void {
        let v = UILabel()
        v.backgroundColor = .green
        v.text = "Sub-Label \(dynaStack.arrangedSubviews.count + 1)"
        dynaStack.addArrangedSubview(v)

        // dispatch scroll-to-bottom on main thread
        // need to do this so contentSize is calculated after
        // new label has been added
        if let sv = dynaStack.superview as? UIScrollView {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                let bottomOffset = CGPoint(x: 0, y: sv.contentSize.height - sv.bounds.size.height + sv.contentInset.bottom)
                if(bottomOffset.y > 0) {
                    sv.setContentOffset(bottomOffset, animated: true)
                }
            }
        }
    }

    func removeLabel() -> Void {
        if dynaStack.arrangedSubviews.count > 0 {
            dynaStack.arrangedSubviews.last?.removeFromSuperview()
        }
    }

}