da1lbi3 da1lbi3 - 1 year ago 110
Swift Question

UIScrollView wrong offset

I have several labels inside an scrollview. Each label is an "page". But the offset isn't right. And I can't find the problem.

My code:

let quantity = 10;
var width : CGFloat = 0.0;

override func viewDidLoad() {

width = self.scrView.frame.width;

for i in 0..<quantity {

let xPos = width * CGFloat(i);
let label = UILabel(frame: CGRect(x: xPos, y: 0, width: width, height: self.scrView.frame.height))
label.textAlignment = .center
label.font = UIFont(name: "Helvetica Neue", size: 50)
label.textColor = UIColor.white
label.text = "\(i + 1)"

label.backgroundColor = .randomColor()

scrView.contentSize.width = width * CGFloat(quantity + 1);


The pink color on the left side is from the previous "page".

enter image description here

And again, note the purple color on the left side from the previous (number 8) page.

enter image description here

The first page seems fine. However the higher the number the greater the offset. I want to cover the whole visible area for 1 label.

Does somebody knows an solution?

Answer Source

Your code works fine for me.

Note that the size of the scrollView can change after viewDidLoad as a result of Auto Layout. A better place to set up your scrollView would be in an override of viewDidLayoutSubviews. The size of the scrollView will be established by then. But be careful, because viewDidLayoutSubviews will run multiple times, so make sure you only set up your scrollView once.

This is not your bug, but your contentSize.width is too big. You don't need to add 1 to quantity since there are exactly quantity labels in your scrollView content area.

scrView.contentSize.width = width * CGFloat(quantity)

Also, Swift doesn't need the ; at the ends of lines, so delete those.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download