表单元格中标签的sizeToFit函数的异常行为

时间:2019-07-03 15:27:18

标签: ios swift uitableview

在使用我的TableView设计之一时,我遇到了问题。我使用false false false true true true 来调整单元格中UILabel的大小。

sizeToFit

当Tableview滚动时,UILabel的宽度变得越来越小,如下面的屏幕截图所示;

enter image description here

根据Apple的文档

Call this method when you want to resize the current view so that it uses the most appropriate amount of space.

我期望大小会相应地增加和减少UILabels的需求。但是它总是收缩而永远不会增长。

说明文件是否具有误导性,或者我有什么遗漏?

更新   约束条件

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以在单元格中使用UIStackView使自动调整大小变得更加容易。

这是布局:

enter image description here

堆栈视图被限制在“ Card View”的所有4个侧面(仅限于contentView的所有4个侧面),每一个都有一些填充。

堆栈视图的属性设置为:

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>