How can I vertically align all my contents of my Table View Cell?

Viewed 1889

I want to make all the contents in my table cell vertical align center.

enter image description here

I want my content to render at the red line

enter image description here


I've tried

via code

func updateTableViewContentInset() {
    let viewHeight: CGFloat = view.frame.size.height
    let tableViewContentHeight: CGFloat = placesTable.contentSize.height
    let marginHeight: CGFloat = (viewHeight - tableViewContentHeight) / 2.0

    self.placesTable.contentInset = UIEdgeInsets(top: marginHeight, left: 0, bottom:  -marginHeight, right: 0)
}

override func viewWillAppear(_ animated: Bool) {
    updateTableViewContentInset()
}

enter image description here


I tried

enter image description here

I got

enter image description here

result

enter image description here

or even via the storyboard, but have not get the desired result that I am looking for yet.

Any hints for me ?

4 Answers

You need to remove the top constraints of the labels and ctrl-drag from the left most label to contentView and select center vertically but note you need to implement heightForRowAt to give the correct height

If you want to center the content you can do the following in storyboard:

  1. For the left side (two labels), add a vertical stack view and constraint it to content view's vertical center and a leading constraint to the content view.

  2. In the stack view add your two labels, the stackview height/width will be set automatically (called intrinsic size, where the view calculates its size according to its content)

  3. For the right side just add the labels and set a constraint to center vertically in the content view. add additional constraints to set them apart as they do now.

Firstly select the two elements in left and add them in vertical stack view like this: enter image description here

Then select the elements that you want to center inside your cell and apply Vertically in container.

enter image description here

For horizontal constraints between elements, select each element and add constraints like this:

enter image description here

I have your cell laid out like this:

enter image description here

The address Top and Bottom labels are contained in a UIStackView with:

Alignment: Leading
Distribution: Fill
Spacing: 4
  • The stack view is constrained Leading to Leading Margin, and Vertically Centered
  • The "miles" label is constrained Trailing to Trailing Margin, and Last Baseline to the "distance" label
  • The "distance" label is constrained Trailing to "miles" Leading, with 8-pts for padding
  • The "distance" label is also constrained Vertically Centered
  • The StackView Trailing is constrained >= to "distance" Leading, with 8-pts for padding
  • and finally, the "distance" label's Compression Resistance is set to 1000 to give it priority (so the address line may get truncated, but the distance value won't)

The result:

enter image description here

Here is the source of the xib file so you can inspect the layout if you run into any problems:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="14109" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
        <capability name="Constraints to layout margins" minToolsVersion="6.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <objects>
        <placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
        <placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
        <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" rowHeight="70" id="luO-Wj-VHn" customClass="VertCenterCellXIB" customModule="SW4Temp" customModuleProvider="target">
            <rect key="frame" x="0.0" y="0.0" width="375" height="70"/>
            <autoresizingMask key="autoresizingMask"/>
            <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="luO-Wj-VHn" id="bdC-Mi-Lfi">
                <rect key="frame" x="0.0" y="0.0" width="375" height="69.5"/>
                <autoresizingMask key="autoresizingMask"/>
                <subviews>
                    <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" alignment="top" spacing="4" translatesAutoresizingMaskIntoConstraints="NO" id="9Ce-Dp-nkn">
                        <rect key="frame" x="16" y="15.5" width="119" height="39"/>
                        <subviews>
                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="39 Cosgrove St" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="xch-Kp-Bi4">
                                <rect key="frame" x="0.0" y="0.0" width="119" height="20.5"/>
                                <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="United States" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="lYb-n3-8pd">
                                <rect key="frame" x="0.0" y="24.5" width="77" height="14.5"/>
                                <fontDescription key="fontDescription" type="system" pointSize="12"/>
                                <nil key="textColor"/>
                                <nil key="highlightedColor"/>
                            </label>
                        </subviews>
                    </stackView>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" horizontalCompressionResistancePriority="1000" text="7.8" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="i1h-WH-LQH">
                        <rect key="frame" x="260" y="9.5" width="53" height="50.5"/>
                        <fontDescription key="fontDescription" type="system" weight="thin" pointSize="42"/>
                        <color key="textColor" red="0.0" green="0.58980089430000004" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <nil key="highlightedColor"/>
                    </label>
                    <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="miles" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="21q-Yj-LDN">
                        <rect key="frame" x="321" y="34.5" width="38" height="19.5"/>
                        <fontDescription key="fontDescription" type="system" pointSize="16"/>
                        <color key="textColor" red="0.0" green="0.58980089430000004" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <nil key="highlightedColor"/>
                    </label>
                </subviews>
                <constraints>
                    <constraint firstItem="i1h-WH-LQH" firstAttribute="centerY" secondItem="bdC-Mi-Lfi" secondAttribute="centerY" id="4vN-dI-N9v"/>
                    <constraint firstItem="9Ce-Dp-nkn" firstAttribute="leading" secondItem="bdC-Mi-Lfi" secondAttribute="leadingMargin" id="595-Oi-wU4"/>
                    <constraint firstItem="9Ce-Dp-nkn" firstAttribute="centerY" secondItem="bdC-Mi-Lfi" secondAttribute="centerY" id="88e-Jn-rRu"/>
                    <constraint firstItem="21q-Yj-LDN" firstAttribute="leading" secondItem="i1h-WH-LQH" secondAttribute="trailing" constant="8" id="LOe-Ph-3ve"/>
                    <constraint firstItem="i1h-WH-LQH" firstAttribute="leading" relation="greaterThanOrEqual" secondItem="9Ce-Dp-nkn" secondAttribute="trailing" constant="8" id="XIw-PU-tKr"/>
                    <constraint firstItem="21q-Yj-LDN" firstAttribute="baseline" secondItem="i1h-WH-LQH" secondAttribute="baseline" id="aBn-DN-9wA"/>
                    <constraint firstAttribute="trailingMargin" secondItem="21q-Yj-LDN" secondAttribute="trailing" id="spV-CW-rmt"/>
                </constraints>
            </tableViewCellContentView>
            <connections>
                <outlet property="bottomAddressLabel" destination="lYb-n3-8pd" id="pcr-TF-F3g"/>
                <outlet property="distanceLabel" destination="i1h-WH-LQH" id="EcP-Xf-U6K"/>
                <outlet property="topAddressLabel" destination="xch-Kp-Bi4" id="vd5-YM-J10"/>
            </connections>
            <point key="canvasLocation" x="35" y="-35"/>
        </tableViewCell>
    </objects>
</document>
Related