Как я могу выровнять по вертикали все мое содержимое ячейки табличного представления? - PullRequest
0 голосов
/ 01 ноября 2018

Я хочу, чтобы все содержимое моей ячейки таблицы было выровнено по центру.

enter image description here

Я хочу, чтобы мой контент отображался красной линией

enter image description here


Я пытался

через код

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


Я пытался

enter image description here

Я получил

enter image description here

результат

enter image description here

или даже через раскадровку, но пока не получили желаемого результата, которого я ищу.

Любые намеки для меня?

Ответы [ 4 ]

0 голосов
/ 02 ноября 2018

У меня твоя клетка разложена так:

enter image description here

Адрес Верхняя и Нижняя метки содержатся в UIStackView с:

Alignment: Leading
Distribution: Fill
Spacing: 4
  • Представление стека ограничено, ведущее к ведущей марже, и вертикально центрировано
  • Метка «миль» ограничена меткой Trailing to Trailing Margin, а последняя базовая линия - меткой «distance»
  • Метка «расстояние» ограничена Трейлинг до «миль», с 8 пунктами для заполнения
  • Метка «расстояние» также ограничена по вертикали по центру
  • StackView Trailing ограничен >= лидирующим «расстоянием», с 8 пунктами для заполнения
  • и, наконец, сопротивление сжатию метки «distance» установлено на 1000, чтобы дать ему приоритет (чтобы строка адреса могла быть усечена, но значение расстояния не будет)

Результат:

enter image description here

Вот источник 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>
0 голосов
/ 01 ноября 2018

Вам нужно убрать верхние ограничения надписей и перетащить Ctrl из самой левой надписи в contentView и выбрать центр по вертикали, но учтите, что вам нужно реализовать heightForRowAt, чтобы задать правильную высоту

0 голосов
/ 01 ноября 2018

Сначала выберите два элемента слева и добавьте их в виде вертикального стека следующим образом: enter image description here

Затем выберите элементы, которые вы хотите центрировать внутри вашей ячейки, и примените Вертикально в контейнере.

enter image description here

Для горизонтальных ограничений между элементами выберите каждый элемент и добавьте ограничения следующим образом:

enter image description here

0 голосов
/ 01 ноября 2018

Если вы хотите центрировать контент, вы можете сделать следующее в раскадровке:

  1. Для левой стороны (две метки) добавьте представление вертикального стека и ограничьте его вертикальным центром представления содержимого и ведущее ограничение для представления содержимого.

  2. В представлении стека добавьте две метки, высота / ширина стека будет установлена ​​автоматически (так называемый внутренний размер, где представление вычисляет свой размер в соответствии с его содержимым)

  3. Для правой стороны просто добавьте метки и установите ограничение по центру по вертикали в представлении содержимого. добавьте дополнительные ограничения, чтобы выделить их, как они делают сейчас.

...