2016年12月17日 星期六

「iOS」ImageView 輪播圖片

要讓ImageView自動輪播圖片,可以很簡單做到,首先拉一個ImageView出來

取一個名字叫myImage



























接著我拉了6張照片進來Assets.xcassets

















開始寫程式


//
//  ViewController.swift
//  imageview
//
//  Created by boywhy chen on 2016/12/17.
//  Copyright © 2016年 boywhy chen. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myImage: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        playImage()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func playImage()
    {
        //圖檔名稱陣列
        var fileName = [ "P1120236.jpg" , "P1120242.jpg" , "P1120257.jpg" , "P1120273.jpg" , "P1120277.jpg" , "P1120288.jpg"]
        
        //init a empty array , for append UIImage
        var arrayImage: [UIImage] = []
        
        //append  UIImage array
        for (var i=0 ;i<fileName.count ; i++)
        {
            arrayImage.append(UIImage(named: fileName[i])!)
        }
        
        //set Animation source
        myImage.animationImages = arrayImage
        
        //play total time  , if you have 6 image , total 12 sec , every one image show 2 sec
        myImage.animationDuration = 12
        
        //play times , if set 0  ,   continue  paly image . 
        myImage.animationRepeatCount = 1
        
        //start play 
        myImage.startAnimating()
        
        
        //stop play 
        //myImage.stopAnimating()
        
        
        
    }
}


由於我只設定播1次,所以在12秒後,會停下來,ImageView變成空白。

參考資料:

Swift: Creating an array of UIImage

http://stackoverflow.com/questions/24172180/swift-creating-an-array-of-uiimage

沒有留言:

張貼留言