当约束到包含多行 UILabel 的 UIStackview 时,UITableViewCell 高度不是动态的

UITableViewCell height not dynamic when constrained to UIStackview containing multi-line UILabels

我有一个包含 UIStackView 的表格视图单元格。 stack view 包含两个可以是多行的标签和底部的另一个 stackview。这就是单元格的显示方式,但有更多的边距。这对超级视图的个人资料图片 ImageView 的顶部和底部有 15 点约束。理想情况下,15pt 的顶部和底部约束将位于堆栈视图上。

当我将堆栈视图的顶部和底部约束添加到父视图时,中间的多行标签被强制为 1 行。

我希望所有标签的顶部和底部边距都能正确显示多行。

如果我将底部标签的垂直阻力设置得比顶部标签高,顶部标签就会消失。

如果我将垂直内容拥抱优先级设置为一个标签,另一个标签将被剪裁。如果我将两个标签 Hugging Priority 设置为相等,则不满足约束条件,它会要求我提高一个。

我不明白其中的逻辑,我希望两个标签都根据内容增加高度,并相应地调整单元格的大小。为什么我需要给一个优先权?

如果我从堆栈视图移除顶部和底部约束到单元格的内容视图,则不必将一个标签的 Content Hugging 优先级设置为高于另一个。但是我想要保证金的顶部和底部约束。

我尝试将标签限制到堆栈视图,但产生了相同的结果。堆栈视图对齐设置为填充。分布设置为按比例填充。更改这些值并没有太大变化。 tableview是预估行高,行高设置为自动维度

有什么建议吗?

同时提供图像视图和堆栈视图:

  • >=15
  • 的顶部和底部约束
  • 中心 Y 约束

您的单元格高度将成为两者中较大的一个,另一个将保持垂直居中。

这是一个例子:

结果:

注意:您还需要调整某些元素的内容拥抱和压缩阻力优先级(这在使用堆栈视图时很常见)。

这是我使用的单元格和视图控制器 类(显然,我只设置了演示此所需的元素):

class StackedCell: UITableViewCell {

    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var descriptionLabel: UILabel!

}

class StackCellTableViewController: UITableViewController {

    var theData : [[String]] = [
        ["John Bradford", "This is short text."],
        ["Tom Bradford", "This is long enough text to cause wrapping."],
        ["Fred Bradford", "This text is also long enough to wrap, but this time onto a couple lines -- which will be no problem."],
        ["Mr. David With a Wrapping Name Bradford", "This is short text"],
        ["Mr. Edward With a Wrapping Name Bradford", "Both labels should have enough text to cause wrapping."],
        ]

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return theData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "StackedCell", for: indexPath) as! StackedCell

        cell.titleLabel.text = theData[indexPath.row][0]
        cell.descriptionLabel.text = theData[indexPath.row][1]

        return cell
    }

}

这里是 Storyboard 的来源,可帮助您顺利上路:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="MSE-mh-zOH">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--Stack Cell Table View Controller-->
        <scene sceneID="diu-E1-9Ab">
            <objects>
                <tableViewController id="mgB-HM-TNh" customClass="StackCellTableViewController" customModule="XC10SWScratch" customModuleProvider="target" sceneMemberID="viewController">
                    <tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="NLY-of-j1O">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                        <prototypes>
                            <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" selectionStyle="default" indentationWidth="10" reuseIdentifier="StackedCell" rowHeight="137" id="8QS-VE-jU8" customClass="StackedCell" customModule="XC10SWScratch" customModuleProvider="target">
                                <rect key="frame" x="0.0" y="28" width="375" height="137"/>
                                <autoresizingMask key="autoresizingMask"/>
                                <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="8QS-VE-jU8" id="Sks-7v-DrQ">
                                    <rect key="frame" x="0.0" y="0.0" width="375" height="136.5"/>
                                    <autoresizingMask key="autoresizingMask"/>
                                    <subviews>
                                        <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="e9C-Vu-DFw" userLabel="ProfileImage">
                                            <rect key="frame" x="16" y="38.5" width="60" height="60"/>
                                            <color key="backgroundColor" red="0.46202266219999999" green="0.83828371759999998" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                            <constraints>
                                                <constraint firstAttribute="width" secondItem="e9C-Vu-DFw" secondAttribute="height" multiplier="1:1" id="6dF-Hg-kn8"/>
                                                <constraint firstAttribute="width" constant="60" id="cAO-Ur-Qay"/>
                                            </constraints>
                                        </imageView>
                                        <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" spacing="4" translatesAutoresizingMaskIntoConstraints="NO" id="lS6-6c-Vgn" userLabel="LabelsStack">
                                            <rect key="frame" x="88" y="36.5" width="226" height="63.5"/>
                                            <subviews>
                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="1000" verticalCompressionResistancePriority="1000" text="John Bradford" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="bi0-SV-Oba">
                                                    <rect key="frame" x="0.0" y="0.0" width="226" height="21.5"/>
                                                    <fontDescription key="fontDescription" type="system" weight="semibold" pointSize="18"/>
                                                    <nil key="textColor"/>
                                                    <nil key="highlightedColor"/>
                                                </label>
                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="1000" verticalCompressionResistancePriority="1000" text="This is the Description Label." textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="VrD-Zq-XEM">
                                                    <rect key="frame" x="0.0" y="25.5" width="226" height="17"/>
                                                    <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                    <nil key="textColor"/>
                                                    <nil key="highlightedColor"/>
                                                </label>
                                                <view contentMode="scaleToFill" verticalHuggingPriority="1000" translatesAutoresizingMaskIntoConstraints="NO" id="TVE-Sc-9ZR" userLabel="StarsView">
                                                    <rect key="frame" x="0.0" y="46.5" width="226" height="17"/>
                                                    <subviews>
                                                        <stackView opaque="NO" contentMode="scaleToFill" verticalHuggingPriority="1000" spacing="8" translatesAutoresizingMaskIntoConstraints="NO" id="Bxs-Tn-foO" userLabel="StarsStack">
                                                            <rect key="frame" x="0.0" y="0.0" width="148" height="17"/>
                                                            <subviews>
                                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="1000" text="★" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="nvJ-Q5-WhG">
                                                                    <rect key="frame" x="0.0" y="0.0" width="16" height="17"/>
                                                                    <fontDescription key="fontDescription" type="system" pointSize="18"/>
                                                                    <color key="textColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                                    <nil key="highlightedColor"/>
                                                                </label>
                                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="1000" text="★" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="QzW-RR-1Er">
                                                                    <rect key="frame" x="24" y="0.0" width="16" height="17"/>
                                                                    <fontDescription key="fontDescription" type="system" pointSize="18"/>
                                                                    <color key="textColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                                    <nil key="highlightedColor"/>
                                                                </label>
                                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="1000" text="★" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="3HC-Vh-iSJ">
                                                                    <rect key="frame" x="48" y="0.0" width="16" height="17"/>
                                                                    <fontDescription key="fontDescription" type="system" pointSize="18"/>
                                                                    <color key="textColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                                    <nil key="highlightedColor"/>
                                                                </label>
                                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="1000" text="★" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="KC3-u8-XWI">
                                                                    <rect key="frame" x="72" y="0.0" width="16" height="17"/>
                                                                    <fontDescription key="fontDescription" type="system" pointSize="18"/>
                                                                    <color key="textColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                                    <nil key="highlightedColor"/>
                                                                </label>
                                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="1000" text="★" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="m51-4b-ADh">
                                                                    <rect key="frame" x="96" y="0.0" width="16" height="17"/>
                                                                    <fontDescription key="fontDescription" type="system" pointSize="18"/>
                                                                    <color key="textColor" red="0.75406885150000003" green="0.75408679249999999" blue="0.75407713649999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                                    <nil key="highlightedColor"/>
                                                                </label>
                                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="1000" text="(53)" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="aJw-Yl-uQh">
                                                                    <rect key="frame" x="120" y="0.0" width="28" height="17"/>
                                                                    <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                                    <color key="textColor" white="0.66666666666666663" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                                                    <nil key="highlightedColor"/>
                                                                </label>
                                                            </subviews>
                                                        </stackView>
                                                    </subviews>
                                                    <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                                    <constraints>
                                                        <constraint firstItem="Bxs-Tn-foO" firstAttribute="top" secondItem="TVE-Sc-9ZR" secondAttribute="top" id="1C6-g6-TFj"/>
                                                        <constraint firstAttribute="bottom" secondItem="Bxs-Tn-foO" secondAttribute="bottom" id="A5M-bL-fmw"/>
                                                        <constraint firstItem="Bxs-Tn-foO" firstAttribute="leading" secondItem="TVE-Sc-9ZR" secondAttribute="leading" id="gBy-fg-xaP"/>
                                                    </constraints>
                                                </view>
                                            </subviews>
                                        </stackView>
                                        <button opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="1000" horizontalCompressionResistancePriority="1000" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="22x-DH-zgf" userLabel="EditButton">
                                            <rect key="frame" x="326" y="53.5" width="33" height="30"/>
                                            <state key="normal" title="EDIT"/>
                                        </button>
                                    </subviews>
                                    <constraints>
                                        <constraint firstAttribute="bottomMargin" relation="greaterThanOrEqual" secondItem="22x-DH-zgf" secondAttribute="bottom" constant="15" id="6ko-9c-f8E"/>
                                        <constraint firstAttribute="bottomMargin" relation="greaterThanOrEqual" secondItem="e9C-Vu-DFw" secondAttribute="bottom" constant="15" id="E8y-Nx-e6k"/>
                                        <constraint firstItem="e9C-Vu-DFw" firstAttribute="centerY" secondItem="Sks-7v-DrQ" secondAttribute="centerY" id="Fsi-Ia-Vh7"/>
                                        <constraint firstItem="22x-DH-zgf" firstAttribute="leading" secondItem="lS6-6c-Vgn" secondAttribute="trailing" constant="12" id="I1T-WO-RhK"/>
                                        <constraint firstItem="22x-DH-zgf" firstAttribute="top" relation="greaterThanOrEqual" secondItem="Sks-7v-DrQ" secondAttribute="topMargin" constant="15" id="Oqf-MF-AyE"/>
                                        <constraint firstItem="lS6-6c-Vgn" firstAttribute="leading" secondItem="e9C-Vu-DFw" secondAttribute="trailing" constant="12" id="Y46-0s-kcr"/>
                                        <constraint firstAttribute="trailingMargin" secondItem="22x-DH-zgf" secondAttribute="trailing" id="c67-Xj-1i7"/>
                                        <constraint firstItem="lS6-6c-Vgn" firstAttribute="top" relation="greaterThanOrEqual" secondItem="Sks-7v-DrQ" secondAttribute="top" constant="15" id="ei6-pz-Bnr"/>
                                        <constraint firstItem="lS6-6c-Vgn" firstAttribute="centerY" secondItem="Sks-7v-DrQ" secondAttribute="centerY" id="mys-LE-jkm"/>
                                        <constraint firstAttribute="bottom" relation="greaterThanOrEqual" secondItem="lS6-6c-Vgn" secondAttribute="bottom" constant="15" id="rHM-XF-n4C"/>
                                        <constraint firstItem="e9C-Vu-DFw" firstAttribute="leading" secondItem="Sks-7v-DrQ" secondAttribute="leadingMargin" id="uP4-26-6Uc"/>
                                        <constraint firstItem="e9C-Vu-DFw" firstAttribute="top" relation="greaterThanOrEqual" secondItem="Sks-7v-DrQ" secondAttribute="topMargin" constant="15" id="x1z-ox-koN"/>
                                        <constraint firstItem="22x-DH-zgf" firstAttribute="centerY" secondItem="Sks-7v-DrQ" secondAttribute="centerY" id="zxj-IG-DbW"/>
                                    </constraints>
                                </tableViewCellContentView>
                                <connections>
                                    <outlet property="descriptionLabel" destination="VrD-Zq-XEM" id="YT1-t7-FtK"/>
                                    <outlet property="titleLabel" destination="bi0-SV-Oba" id="wu2-Ty-yge"/>
                                </connections>
                            </tableViewCell>
                        </prototypes>
                        <connections>
                            <outlet property="dataSource" destination="mgB-HM-TNh" id="Fsm-c0-afH"/>
                            <outlet property="delegate" destination="mgB-HM-TNh" id="Uht-Ga-aoa"/>
                        </connections>
                    </tableView>
                    <navigationItem key="navigationItem" id="VCY-uQ-EQ7"/>
                </tableViewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="uPF-XE-23l" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="924" y="737.18140929535241"/>
        </scene>
        <!--Navigation Controller-->
        <scene sceneID="F8k-zt-Ijc">
            <objects>
                <navigationController automaticallyAdjustsScrollViewInsets="NO" id="MSE-mh-zOH" sceneMemberID="viewController">
                    <toolbarItems/>
                    <navigationBar key="navigationBar" contentMode="scaleToFill" insetsLayoutMarginsFromSafeArea="NO" id="9T6-F6-vim">
                        <rect key="frame" x="0.0" y="20" width="375" height="44"/>
                        <autoresizingMask key="autoresizingMask"/>
                    </navigationBar>
                    <nil name="viewControllers"/>
                    <connections>
                        <segue destination="mgB-HM-TNh" kind="relationship" relationship="rootViewController" id="Dpn-ba-QhM"/>
                    </connections>
                </navigationController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="zHK-UX-1Sq" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="-15.199999999999999" y="737.18140929535241"/>
        </scene>
    </scenes>
</document>