标签在水平集合视图中被裁剪swift

sd2nnvve  于 2023-03-22  发布在  Swift
关注(0)|答案(3)|浏览(106)

所以我需要做的就是制作一个标签的水平列表,为此我使用了一个集合视图。它看起来像预期的那样工作,但我的标签被裁剪,只有一半的标签显示如下:

这就是它应该看起来的样子:

我的vc代码:

class STViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    
    
    let data: [stmodel] = [stmodel(text: "صف أول"),
                           stmodel(text: "صف ثاني"),
                           stmodel(text: "صف ثالث")]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
        collectionView.delegate = self
        // Do any additional setup after loading the view.
    }
    

    

}

extension STViewController : UICollectionViewDataSource,UICollectionViewDelegate {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! ClassesCollectionViewCell
        cell.configure(with: data[indexPath.row])
        return cell;
    }
}

谢谢大家!

gkn4icbw

gkn4icbw1#

关于您的问题,您可以使用UICollectionViewDelegateFlowLayout解决它。

extension STViewController: UICollectionViewDelegateFlowLayout {
   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        CGSize(width: 70, height: 80)
    }
}

要了解有关UICollectionViewDelegateFlowLayout的更多信息,您可以阅读Apple文档。[链接]:https://developer.apple.com/documentation/uikit/uicollectionviewdelegateflowlayout

1sbrub3j

1sbrub3j2#

我遇到了同样的问题,并找到了两个有效的方法来解决这个问题。

1.您可以新建一个UICollectionViewFlowLayout的示例,并将其设置为您的UICollectionViewcollectionViewLayout,这样就可以轻松控制您的UICollectionViewitemSize,使其不被裁剪。为此,请按照以下方式编辑您的viewDidLoad()

override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
        collectionView.delegate = self
    
        let layout = UICollectionViewFlowLayout()
        layout.itemSize  = CGSize(width: 100, height: 40)
        layout.scrollDirection = .horizontal
        collectionView.collectionViewLayout = layout
    }

2.您可以使用UICollectionViewDelegateFlowLayout协议的sizeForItemAt方法,同时也可以设置UICollectionView的项目大小,只需添加以下扩展即可。

extension ViewController: UICollectionViewDelegateFlowLayout{
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
            return CGSize(width: 100, height: 40)
        }
    }

这应该能解决你的问题。

nwo49xxi

nwo49xxi3#

您不需要设置layout.itemSize,也不需要实现sizeForItemAt
事实上,如果你想要可变宽度的单元格(看起来是你想要的),那么使用这两种方法都不会给予你想要的结果。
由于您使用的是情节提要,请确保集合视图“估计单元格大小”为“自动”:

在开发过程中,它可以帮助您为UI元素提供对比色,以便更容易看到框架。
例如,我的故事板看起来像这样:

所以,这就是运行时的样子……
首先,使用“开发”颜色,加上集合视图周围的红色边框,以便我们可以看到它的框架:

然后,使用“运行时”颜色:

没有红色边框:

为了得到它我用了你的代码...
你没有提供你的stmodel,所以我使用了这个:

struct stmodel {
    var text: String = ""
}

和一个简单的细胞类来尝试匹配你的图像:

class ClassesCollectionViewCell: UICollectionViewCell {
    @IBOutlet var theLabel: UILabel!
    
    func configure(with: stmodel) {
        theLabel.text = with.text
        
        // un-comment these after development
        //  or set them in Storyboard
        theLabel.backgroundColor = .clear
        contentView.backgroundColor = .white
    }
}

和控制器类-注意没有.itemSizesizeForItemAt代码:

class STViewController: UIViewController {
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    
    let data: [stmodel] = [stmodel(text: "صف أول"),
                           stmodel(text: "صف ثاني"),
                           stmodel(text: "صف ثالث"),
                           stmodel(text: "العنصر الرابع الأطول")
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.dataSource = self
        collectionView.delegate = self
        // Do any additional setup after loading the view.
        
        // during development, so we can see the collection view frame
        // comment (or delete them) after development
        //collectionView.layer.borderColor = UIColor.red.cgColor
        //collectionView.layer.borderWidth = 1
    }
    
}

extension STViewController : UICollectionViewDataSource,UICollectionViewDelegate {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! ClassesCollectionViewCell
        cell.configure(with: data[indexPath.row])
        return cell;
    }
}

这是故事板的来源:

<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="21507" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="EkW-Jg-PCP">
    <device id="retina6_12" orientation="portrait" appearance="light"/>
    <dependencies>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="21505"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="System colors in document resources" minToolsVersion="11.0"/>
        <capability name="collection view cell content view" minToolsVersion="11.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="xyK-2E-YPW">
            <objects>
                <viewController id="EkW-Jg-PCP" customClass="STViewController" customModule="cvtemp" customModuleProvider="target" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="UzK-83-pcT">
                        <rect key="frame" x="0.0" y="0.0" width="393" height="852"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <collectionView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" dataMode="prototypes" translatesAutoresizingMaskIntoConstraints="NO" id="nXQ-0Y-BK6">
                                <rect key="frame" x="40" y="119" width="313" height="60"/>
                                <color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                                <constraints>
                                    <constraint firstAttribute="height" constant="60" id="CcK-kk-cEE"/>
                                </constraints>
                                <collectionViewFlowLayout key="collectionViewLayout" scrollDirection="horizontal" automaticEstimatedItemSize="YES" minimumLineSpacing="10" minimumInteritemSpacing="10" id="u6U-pC-5Jh">
                                    <size key="itemSize" width="128" height="40"/>
                                    <size key="headerReferenceSize" width="0.0" height="0.0"/>
                                    <size key="footerReferenceSize" width="0.0" height="0.0"/>
                                    <inset key="sectionInset" minX="0.0" minY="0.0" maxX="0.0" maxY="0.0"/>
                                </collectionViewFlowLayout>
                                <cells>
                                    <collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="myCell" id="8jb-8e-kTy" customClass="ClassesCollectionViewCell" customModule="cvtemp" customModuleProvider="target">
                                        <rect key="frame" x="0.0" y="16" width="73.333333333333329" height="28.333333333333329"/>
                                        <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                        <collectionViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" insetsLayoutMarginsFromSafeArea="NO" id="t3x-HA-Fd9">
                                            <rect key="frame" x="0.0" y="0.0" width="73.333333333333329" height="28.333333333333329"/>
                                            <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
                                            <subviews>
                                                <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="gce-1u-VwE">
                                                    <rect key="frame" x="16.000000000000004" y="4" width="41.333333333333343" height="20.333333333333332"/>
                                                    <color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                    <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                    <nil key="textColor"/>
                                                    <nil key="highlightedColor"/>
                                                </label>
                                            </subviews>
                                            <color key="backgroundColor" systemColor="systemYellowColor"/>
                                            <constraints>
                                                <constraint firstAttribute="trailing" secondItem="gce-1u-VwE" secondAttribute="trailing" constant="16" id="Oux-2u-34y"/>
                                                <constraint firstItem="gce-1u-VwE" firstAttribute="leading" secondItem="t3x-HA-Fd9" secondAttribute="leading" constant="16" id="j3p-5L-sQt"/>
                                                <constraint firstItem="gce-1u-VwE" firstAttribute="top" secondItem="t3x-HA-Fd9" secondAttribute="top" constant="4" id="jJk-HA-y7p"/>
                                                <constraint firstAttribute="bottom" secondItem="gce-1u-VwE" secondAttribute="bottom" constant="4" id="uYo-Ae-NHe"/>
                                            </constraints>
                                        </collectionViewCellContentView>
                                        <connections>
                                            <outlet property="theLabel" destination="gce-1u-VwE" id="9bk-kQ-LCV"/>
                                        </connections>
                                    </collectionViewCell>
                                </cells>
                            </collectionView>
                        </subviews>
                        <viewLayoutGuide key="safeArea" id="yKI-9a-aDK"/>
                        <color key="backgroundColor" red="0.75663715600000003" green="0.88705736400000001" blue="0.9215784669" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="nXQ-0Y-BK6" firstAttribute="leading" secondItem="yKI-9a-aDK" secondAttribute="leading" constant="40" id="3Jy-g1-UwM"/>
                            <constraint firstItem="nXQ-0Y-BK6" firstAttribute="top" secondItem="yKI-9a-aDK" secondAttribute="top" constant="60" id="UPE-tv-i1d"/>
                            <constraint firstItem="yKI-9a-aDK" firstAttribute="trailing" secondItem="nXQ-0Y-BK6" secondAttribute="trailing" constant="40" id="fkt-Lq-iUy"/>
                        </constraints>
                    </view>
                    <connections>
                        <outlet property="collectionView" destination="nXQ-0Y-BK6" id="BFH-sB-sph"/>
                    </connections>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="ZoX-CK-vDN" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="351.90839694656489" y="106.33802816901409"/>
        </scene>
    </scenes>
    <resources>
        <systemColor name="systemYellowColor">
            <color red="1" green="0.80000000000000004" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
        </systemColor>
    </resources>
</document>

相关问题