循环时,图像不会添加到 UIImageView

while looping, Images are not adding to UIImageView

我正在尝试在 swift 中自动滚动图像。我在下面尝试过。我正在尝试滚动 swift 编码,而不是 StoryBoard。它滚动得很好。但是,图像不会添加到图像视图中。但是,UIImageView bgcolour 已更改为绿色。我的编码如下。

请指导我。

    var str_1 : String = "one.jpg"
    var str_2 : String = "two.jpg"

    let img_1 : UIImage = UIImage(named: str_1)!
    let img_2 : UIImage = UIImage(named: str_2)!

    img_arr.addObject(img_1)
    img_arr.addObject(img_2)

    scroll_view = UIScrollView(frame: CGRectMake(0, 200, 320, 130))

    for(var y : Int = 0; y < img_arr.count; y++)
    {


        //scr_img_vw = UIImageView(image: img_1)
        //scr_img_vw.addSubview(UIImageView(image: img_arr.objectAtIndex(y) as UIImage))
        scr_img_vw = UIImageView(image: img_arr.objectAtIndex(y) as UIImage)
        //scr_img_vw.image = UIImage(named: img_arr.objectAtIndex(y) as NSString)
        scr_img_vw = UIImageView(frame: CGRectMake(320 * CGFloat(y), 0, 320, 130))
        scr_img_vw.backgroundColor = UIColor.greenColor()

        self.scroll_view.addSubview(scr_img_vw)


    }
        self.view.addSubview(scroll_view)
        scroll_view.contentSize = CGSizeMake(scroll_view.frame.size.width * CGFloat(img_arr.count), 130)
        scroll_view.scrollEnabled = true
        scroll_view.pagingEnabled = true
        scroll_view.bounces = true

您正在分配图像两次。改变for循环如下:

for(var y : Int = 0; y < img_arr.count; y++)
{
    scr_img_vw = UIImageView(image: img_arr.objectAtIndex(y) as UIImage)
    scr_img_vw.frame = CGRectMake(320 * CGFloat(y), 0, 320, 130))
    scr_img_vw.backgroundColor = UIColor.greenColor()

    self.scroll_view.addSubview(scr_img_vw)
}

更好的swift方式是这样的:

let img1 = UIImage(named: "one.jpg")!
let img2 = UIImage(named: "two.jpg")!

var imageArray = [UIImage]()
imageArray.append(img1)
imageArray.append(img2)

for (index, image) in enumerate(imageArray) {
    var imageView = UIImageView(image: image)
    imageView.frame = CGRectMake(320 * CGFloat(index), 0, 320, 130))
    self.scrollView.addSubview(imageView)
}