使用Swift中的水平图像(如Youtube应用程序)滚动查看图像

时间:2016-01-12 16:02:33

标签: ios swift image youtube uiscrollview

我想学习Swift,我想用ScrollView创建一个类似于YouTube应用程序的应用程序。 The ScrollView I want to make

我在故事板中制作的滚动视图。 我尝试使用此代码:

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)

但它不起作用。只有“ImageGrün.png”在屏幕上,而ScrollView不起作用。

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

除了一次,您没有递增索引。 index = 0,然后用index ++递增它,为你提供数组索引为1的图片。你想使用for循环。

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)

这样您就不需要索引,因为Swifts快速枚举会为您处理。有关详细信息,请查看此链接。https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-ID121