如何垂直对齐 Table View Cell 中的所有内容?

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

我想让 table 单元格中的所有内容垂直居中。

我希望我的内容呈现在红线处


我试过了

通过代码

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()
}


我试过了

我得到了

结果

甚至通过情节提要,但还没有得到我想要的结果。

对我有什么提示吗?

如果您想将内容居中,您可以在情节提要中执行以下操作:

  1. 对于左侧(两个标签),添加垂直堆栈视图并将其约束到内容视图的垂直中心和内容视图的前导约束。

  2. 在堆栈视图中添加您的两个标签,堆栈视图height/width将自动设置(称为固有大小,视图根据其内容计算其大小)

  3. 对于右侧,只需添加标签并设置约束以在内容视图中垂直居中。添加额外的约束以像现在一样将它们分开。

您需要删除标签的顶部约束并按住 Ctrl 键从最左侧的标签拖动到 contentView 并 select 垂直居中,但请注意您需要实施 heightForRowAt 以提供正确的高度

首先select左边的两个元素,然后将它们添加到垂直堆栈视图中,如下所示:

然后 select 您想要在单元格内居中并在容器中垂直应用的元素。

对于元素之间的水平约束,select 每个元素并添加这样的约束:

我把你的手机布置成这样:

地址顶部和底部标签包含在 UIStackView 中,其中:

Alignment: Leading
Distribution: Fill
Spacing: 4
  • 堆栈视图受约束 Leading to Leading Margin,并且垂直居中
  • "miles" 标签被限制为 Trailing 到 Trailing Margin,Last Baseline 到 "distance" 标签
  • "distance" 标签限制为 "miles" 前导,填充 8 磅
  • "distance" 标签也被约束为垂直居中
  • StackView 尾部被限制为 >= 到 "distance" 前导,填充 8 磅
  • 最后,"distance" 标签的压缩阻力设置为 1000 以给予它优先权(因此地址线可能会得到 t运行,但距离值不会' t)

结果:

这是 xib 文件的源代码,如果您 运行 遇到任何问题,您可以检查布局:

<?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>