Search code examples
iosswiftxcodeuiscrollview

How to edit UIScrollView size?


I'm trying to build this:

example

But instead, I have this: example2

I haven't started working on background color or changing the slide's background color when selected yet.

My error right now is that I can't get the sizes right (you can tell that when I scroll to the end, it stops at slide 2).

How do I make the frame and slides fit correctly? (each slide is 188 width and 153 height).

Here's my code:

func setupSlideScrollView(slides : [Slide]) {
        scrollView.frame = CGRect(x: 0, y: 0, width: 200, height: 160)
        scrollView.contentSize = CGSize(width: 188 * CGFloat(slides.count), height: 153)
        scrollView.isPagingEnabled = true

        for i in 0 ..< 3 {
            slides[i].frame = CGRect(x: view.frame.width * CGFloat(i), y: 0, width: 188, height: 153)
            slides[i].backgroundColor = UIColor.red
            scrollView.addSubview(slides[i])
        }
    }

For all the code, I'm following this tutorial (except Step 10+ since I don't need animation): https://medium.com/@anitaa_1990/create-a-horizontal-paging-uiscrollview-with-uipagecontrol-swift-4-xcode-9-a3dddc845e92


Solution

  • You are not giving the correct frame to the cells or tickets inside the scrollview.

    var lastCellMaxX: CGFloat = 0
        var constantSpacingBetweenCell: CGFloat = 10
    
        for i in 0 ..< 3 {
            slides[i].frame = CGRect(x: lastCellMaxX, y: 0, width: 188, height: 153)
            slides[i].backgroundColor = UIColor.red
            scrollView.addSubview(slides[i])
            lastCellMaxX += 188 + constantSpacingBetweenCell
        }
    

    I didn't get what is view.frame and I think that is also of no use in your case. Store the lastcellMaxX which is cell.origin.x + cellwidth + spacingBetweenCell, That will be the x while giving frame to the next view