Reputation:
I want to learn Swift and I want to make an app with a ScrollView like it is in the YouTube App.
The scrollview I make in the storyboard. I try it with this code:
let myImages = ["ImageGelb.png","ImageGrün.png","ImageRot.png"]
let imageWidth:CGFloat = 66
let imageHeight:CGFloat = 66
var xPosition:CGFloat = 0
var scrollViewSize:CGFloat=0
var index=0
index<=myImages.count
index++
let myImage:UIImage = UIImage(named: myImages[index])!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.frame.size.width = imageWidth
myImageView.frame.size.height = imageHeight
myImageView.frame.origin.x = xPosition
myImageView.frame.origin.y = 10
ScrollViewNeuesFreunde.addSubview(myImageView)
xPosition += imageWidth
scrollViewSize += imageWidth
ScrollViewNeuesFreunde.contentSize = CGSize(width: scrollViewSize, height: imageHeight)
but it doesn´t work. Only the "ImageGrün.png" is on the screen and the ScrollView does´t work.
Could someone help me?
Upvotes: 2
Views: 3804
Reputation: 2447
You are not incrementing your index except for one time. index = 0, then you incremented it with index++, giving you the picture at index 1 of your array. You want to use a for loop.
let myImages = ["ImageGelb.png","ImageGrün.png","ImageRot.png"]
let imageWidth:CGFloat = 66
let imageHeight:CGFloat = 66
var xPosition:CGFloat = 0
var scrollViewSize:CGFloat=0
for image in myImages {
let myImage:UIImage = UIImage(named: image)!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.frame.size.width = imageWidth
myImageView.frame.size.height = imageHeight
myImageView.frame.origin.x = xPosition
myImageView.frame.origin.y = 10
ScrollViewNeuesFreunde.addSubview(myImageView)
xPosition += imageWidth
scrollViewSize += imageWidth
}
ScrollViewNeuesFreunde.contentSize = CGSize(width: scrollViewSize, height: imageHeight)
This way you don't need an index, as Swifts fast enumeration takes care of it for you. For more on this check out this link.https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID121
Upvotes: 3