Adib
Adib

Reputation: 1324

Swift: Adding UILabel to UIScrollView fails to scroll

I am dynamically creating my UILabels for a tiny calculator. The calculator takes two inputs, number of days and an initial pay, and pumps out the total money made for each day. The calculator takes the initial payment, doubles it, and provides an answer in this form:

On day 1, daily pay earned was $2.00
Total pay earned was $2.00
On day 2, daily pay earned was $4.00
Total pay earned was $6.00
On day 3, daily pay earned was $8.00
Total pay earned was $14.00

The following is a screenshot of the interface: https://www.dropbox.com/s/wunbtzyqzenrwru/Screenshot%202015-04-27%2002.40.44.png?dl=0

Along with the StoryBoard: https://www.dropbox.com/s/pzuouje60x7v7k0/Screenshot%202015-04-27%2002.41.49.png?dl=0

Where

@IBOutlet weak var ScrollView: UIScrollView!

The following is the operation I coded to generate the labels. The problem comes from the last line most likely.

for comments in printArr {
    println(comments)
    var label = UILabel(frame: CGRectMake(0, 0, 300, 42))
    label.numberOfLines = 2
    label.backgroundColor = UIColor(red: 0.988, green: 0.431, blue: 0.318, alpha: 1.0)
    label.textColor = UIColor.whiteColor()
    label.center = CGPointMake(200, 0 + spacer )
    label.textAlignment = NSTextAlignment.Center
    label.font = UIFont(name: label.font.fontName, size: 12)
    label.text = comments
    spacer = spacer + 50
    self.ScrollView.addSubview(label)
}

Any pointers would be greatly appreciated!

Upvotes: 2

Views: 4160

Answers (2)

gutenmorgenuhu
gutenmorgenuhu

Reputation: 2362

You have to set a proper scrollView.contentSize. This is the rectangle, which you can scroll over. For example, this code sets the contentView to 2 times the height of the UIWindow:

let fullScreenRect = UIScreen.mainScreen().applicationFrame
let scrollView = UIScrollView(frame: fullScreenRect)
scrollView.contentSize = CGSizeMake(fullScreenRect.width, fullScreenRect.height*2.0)

Upvotes: 3

ljk321
ljk321

Reputation: 16770

Simply adding subview is not enough. You need to set the contentSize of scroll view to make it scroll.

self.ScrollView.contentSize = TOTAL_SIZE_OF_ALL_YOUR_LABEL

Upvotes: 5

Related Questions