Reputation: 239
I'm trying to build this:
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
Upvotes: 0
Views: 111
Reputation: 57
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
Upvotes: 1
Reputation: 2430
You have to add the space between two slides in the width parameter of scrollview.
In scrollview the content size is the total size of the content you are adding. so, if there is a space between two slides or if you have leading and trailing space then you have to add that total space in content size of scrollview.
For example, If the space between two slides is 10 then, the modified content size of scrollView is as below.
scrollView.contentSize = CGSize(width: 188 * CGFloat(slides.count) + CGFloat((slides.count - 1) * 10), height: 153)
Upvotes: 0