Неожиданное поведение функции sizeToFit метки в ячейке таблицы - PullRequest
0 голосов
/ 03 июля 2019

Во время работы над одним из моих дизайнов TableView у меня возникла проблема.Я использовал sizeToFit для определения размера UILabel в ячейке.

let cell = tableView.dequeueReusableCell(withIdentifier: " DataCell ", for: indexPath) as! DataCell

    let item = data[indexPath.row - 1].copy() as! Data

    cell.nameLabel.numberOfLines = 0
    cell.nameLabel.text = item.name
    cell.nameLabel.sizeToFit()

Когда прокручивается таблица, ширина UILabel становится все меньше и меньше, как на скриншоте ниже;

enter image description here

В соответствии с документацией Apple

Вызывайте этот метод, если вы хотите изменить размер текущего представления, чтобы оно использовало наиболее подходящий объем пространства.

Я ожидал, что размер увеличивается и уменьшается соответственно потребности UILabels.Но оно всегда сжимается и никогда не увеличивается.

Документация вводит в заблуждение или я что-то упускаю?

Обновления Ограничения

enter image description here

1 Ответ

2 голосов
/ 03 июля 2019

Вы можете использовать UIStackView в своей ячейке, чтобы упростить автоматическое изменение размеров.

Вот макет:

enter image description here

Представление стека ограничено всеми четырьмя сторонами «Представления карты» (которое ограничено всеми четырьмя сторонами ContentView), каждая с некоторым заполнением.

Свойства представления стека установлены на:

Axis: Horizontal
Alignment: Center
Distribution: Fill
Spacing: 8

Результат:

enter image description here

Как вы увидите в коде, не нужно вызывать sizeToFit() или делать какие-либо вычисления высоты ... все это обрабатывается с помощью автоматического макета:

//
//  PratikTableViewController.swift
//
//  Created by Don Mag on 7/3/19.
//

import UIKit

class CardView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() -> Void {
        layer.borderWidth = 1
        layer.borderColor = UIColor(white: 0.75, alpha: 1.0).cgColor
        layer.cornerRadius = 8
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 2)
        layer.shadowOpacity = 0.5
        layer.masksToBounds = false
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
    }
}

class RoundButton: UIButton {

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = bounds.height * 0.5
    }

}

class EzineLocationsCell: UITableViewCell {

    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var callButton: RoundButton!
    @IBOutlet var NavigateButton: RoundButton!

}

class PratikTableViewController: UITableViewController {

    let nameList: [String] = [
        "Ezine Hukumet Konagi",
        "Ezine Belediyesi",
        "Emniyet Muduruigu",
        "This name is long and will need to word-wrap",
        "This label will have a lot of text. So much that it will need to wrap onto four lines, showing the vertical centering of the buttons",
        "Jandarma",
        "PTT",
        "Otogar",
        ]

    var theData: [[String : Any]] = [[String : Any]]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // create 4 sets of names so we can scroll
        // randomly show/hide Call Button
        // unless it's the 5th name (really, really long) and then always show the call button
        for i in 1...4 {
            for j in 0..<nameList.count {
                let d: [String : Any] = [
                    "name" : "\(i) " + nameList[j],
                    "showCall" : (j == 4) ? true : Bool.random(),
                ]
                theData.append(d)
            }
        }

    }

    // MARK: - Table view data source

    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: "EzineLocationsCell", for: indexPath) as! EzineLocationsCell

        let dict = theData[indexPath.row]

        if let theName = dict["name"] as? String {
            cell.nameLabel.text = theName
        }

        if let showCall = dict["showCall"] as? Bool {
            cell.callButton.isHidden = !showCall
        }

        return cell
    }

}

и вот исходный код раскадровки, чтобы вам было легко просматривать макет:

<?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="dTy-oX-19M">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--Pratik Table View Controller-->
        <scene sceneID="Fyn-9g-b8b">
            <objects>
                <tableViewController id="dTy-oX-19M" customClass="PratikTableViewController" customModule="LaunchTest2" customModuleProvider="target" sceneMemberID="viewController">
                    <tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="5oi-fi-NeU">
                        <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="EzineLocationsCell" rowHeight="118" id="hfx-tX-pFp" customClass="EzineLocationsCell" customModule="LaunchTest2" customModuleProvider="target">
                                <rect key="frame" x="0.0" y="28" width="375" height="118"/>
                                <autoresizingMask key="autoresizingMask"/>
                                <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" preservesSuperviewLayoutMargins="YES" insetsLayoutMarginsFromSafeArea="NO" tableViewCell="hfx-tX-pFp" id="ykS-rx-6LF">
                                    <rect key="frame" x="0.0" y="0.0" width="375" height="118"/>
                                    <autoresizingMask key="autoresizingMask"/>
                                    <subviews>
                                        <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="JxN-9f-ldF" customClass="CardView" customModule="LaunchTest2" customModuleProvider="target">
                                            <rect key="frame" x="15" y="10" width="345" height="98"/>
                                            <subviews>
                                                <stackView opaque="NO" contentMode="scaleToFill" alignment="center" spacing="8" translatesAutoresizingMaskIntoConstraints="NO" id="cxa-1s-aGX">
                                                    <rect key="frame" x="10" y="16" width="325" height="66"/>
                                                    <subviews>
                                                        <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="PWR-Cn-Ng4">
                                                            <rect key="frame" x="0.0" y="24" width="235" height="18"/>
                                                            <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                                            <fontDescription key="fontDescription" type="system" pointSize="15"/>
                                                            <nil key="textColor"/>
                                                            <nil key="highlightedColor"/>
                                                        </label>
                                                        <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="RDg-A2-rHC" customClass="RoundButton" customModule="LaunchTest2" customModuleProvider="target">
                                                            <rect key="frame" x="243" y="14.5" width="37" height="37"/>
                                                            <color key="backgroundColor" red="0.16078431369999999" green="0.62352941179999999" blue="0.81960784310000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                            <constraints>
                                                                <constraint firstAttribute="height" constant="37" id="3Sa-jq-ghq"/>
                                                                <constraint firstAttribute="width" constant="37" id="5ra-3x-MY3"/>
                                                            </constraints>
                                                            <state key="normal" title="C">
                                                                <color key="titleColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                                            </state>
                                                        </button>
                                                        <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="ks8-6f-wmE" customClass="RoundButton" customModule="LaunchTest2" customModuleProvider="target">
                                                            <rect key="frame" x="288" y="14.5" width="37" height="37"/>
                                                            <color key="backgroundColor" red="0.16078431369999999" green="0.62352941179999999" blue="0.81960784310000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                            <constraints>
                                                                <constraint firstAttribute="width" constant="37" id="0IC-0P-15W"/>
                                                                <constraint firstAttribute="height" constant="37" id="VVP-Ek-Nhr"/>
                                                            </constraints>
                                                            <state key="normal" title="N">
                                                                <color key="titleColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                                            </state>
                                                        </button>
                                                    </subviews>
                                                </stackView>
                                            </subviews>
                                            <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                            <constraints>
                                                <constraint firstAttribute="trailing" secondItem="cxa-1s-aGX" secondAttribute="trailing" constant="10" id="1u3-g7-77F"/>
                                                <constraint firstItem="cxa-1s-aGX" firstAttribute="top" secondItem="JxN-9f-ldF" secondAttribute="top" constant="16" id="pPb-bf-6dG"/>
                                                <constraint firstAttribute="bottom" secondItem="cxa-1s-aGX" secondAttribute="bottom" constant="16" id="qAH-rN-2w0"/>
                                                <constraint firstItem="cxa-1s-aGX" firstAttribute="leading" secondItem="JxN-9f-ldF" secondAttribute="leading" constant="10" id="z5J-XN-CXT"/>
                                            </constraints>
                                        </view>
                                    </subviews>
                                    <constraints>
                                        <constraint firstItem="JxN-9f-ldF" firstAttribute="leading" secondItem="ykS-rx-6LF" secondAttribute="leading" constant="15" id="C92-v8-MWV"/>
                                        <constraint firstItem="JxN-9f-ldF" firstAttribute="top" secondItem="ykS-rx-6LF" secondAttribute="top" constant="10" id="R3b-M4-UUP"/>
                                        <constraint firstAttribute="bottom" secondItem="JxN-9f-ldF" secondAttribute="bottom" constant="10" id="Tqd-9U-xRU"/>
                                        <constraint firstAttribute="trailing" secondItem="JxN-9f-ldF" secondAttribute="trailing" constant="15" id="WBy-wV-S9n"/>
                                    </constraints>
                                </tableViewCellContentView>
                                <connections>
                                    <outlet property="NavigateButton" destination="ks8-6f-wmE" id="gil-V3-IY3"/>
                                    <outlet property="callButton" destination="RDg-A2-rHC" id="YcG-9I-q4U"/>
                                    <outlet property="nameLabel" destination="PWR-Cn-Ng4" id="cIv-Of-uyd"/>
                                </connections>
                            </tableViewCell>
                        </prototypes>
                        <connections>
                            <outlet property="dataSource" destination="dTy-oX-19M" id="EPC-XV-ThJ"/>
                            <outlet property="delegate" destination="dTy-oX-19M" id="hGj-VV-0UD"/>
                        </connections>
                    </tableView>
                </tableViewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="LTW-7e-vVt" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="128.80000000000001" y="174.96251874062969"/>
        </scene>
    </scenes>
</document>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...