简体   繁体   中英

UICollectionView - Cells shouldn't scroll outside the view

Situation:

I use the UITableViewController with static table cells designed in Storyboard. In my first UITableViewCell I implemented a nice UICollectionView .

However there is one problem: The UICollectionViewCell moves out of the frame when I scroll through them. They should stop only in the right positions. 在此处输入图片说明

Code:

import UIKit

class HomeTableViewController: UITableViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var topSliderCollectionView: UICollectionView!

var topSliderElement = [TopSliderElement]()    

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "slider cell", for: indexPath) as! HomeSliderCollectionViewCell   
        let slider = topSliderElement[indexPath.row]

        cell.titleLbl.text = slider.tile
        cell.descriptionLBL.text = slider.description

        return cell
    }   
}

I tried this: This is a possible solution, but it's not working because I don't use a normal UIViewController .

Question: How can I control the cells so that they stop at the right position in the view?

You will have to set your cells width to be the same with as your view.frame.width for this to work properly. If you have any spacing on the sides of your cell (which you do), you'll have to add those together and then minus that from the width. Ie, view.frame.width - 16 . Once you've done this, you'll have to set isPagingEnabled to true in your UICollecitonView - this will lock the cell to the centre of the screen when you stop scrolling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM