skip to Main Content

So all I need is to make a horizontal list of just labels and for this I used a collection view. it looks like it works as expected but my label gets cropped and only half the label shows just like this:

enter image description here

and this is how it is supposed to look like:

enter image description here

my vc code:

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;
    }
}

thank you!

3

Answers


  1. Regarding your problem, you can solve it by using UICollectionViewDelegateFlowLayout.

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

    To learn more about UICollectionViewDelegateFlowLayout, you can read the Apple documentation. [link]: https://developer.apple.com/documentation/uikit/uicollectionviewdelegateflowlayout

    Login or Signup to reply.
  2. I faced the same issue and found 2 effective way to solve that.

    1. You can create a new instance of UICollectionViewFlowLayout and set that as the collectionViewLayout of your UICollectionView. By doing this, you can easily control the itemSize of your UICollectionView so that it doesn’t get cropped. To achieve this, edit your viewDidLoad() in the following way.

        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. You can use the sizeForItemAt method of UICollectionViewDelegateFlowLayout protocol. This will also allow you to set the size for the item of UICollectionView. Just by simply adding the following extension you can achieve that.

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

    This should solve your issue.

    Login or Signup to reply.
  3. You do not need to set layout.itemSize, and you do not need to implement sizeForItemAt.

    In fact, if you want variable-width cells (which it looks like you want), then using either of those will not give you the desired results.

    Since you are using Storyboard, make sure your collection view Estimated Cell Size is Automatic:

    enter image description here

    It can help during development to give your UI elements contrasting colors to make it easy to see the frames.

    For example, my Storyboard looks like this:

    enter image description here

    So, here’s how that looks at run-time…

    First, with the "development" colors, plus a red-border around the collection view so we can see its frame:

    enter image description here

    Then, with "run-time" colors:

    enter image description here

    and without the red border:

    enter image description here

    To get that, I used your code…

    You didn’t provide your stmodel so I used this:

    struct stmodel {
        var text: String = ""
    }
    

    and a simple cell class to try and match your images:

    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
        }
    }
    

    and the controller class – note there is no .itemSize or sizeForItemAt code:

    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;
        }
    }
    

    and here’s the Storyboard source:

    <?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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search