2016年4月21日 星期四

iOS Swift Photo Gallery Collection View 照片 相簿

iOS Swift的相簿使用
1.建立專案後,拉一個Collection View


2.拉一個Image View進去Collection View Cell裡面

3.點選Collection View Cell -> 在Identifier輸入名稱 這裡設定cell

4.在Collection View點右鍵 ->連結dataSource與delegate到View Controller


5.建立一個Cell.swift檔案,點選cell,在Class選擇Cell
接著把Image View拉過去建立 var imgView

import UIKit

class Cell: UICollectionViewCell {
    

    @IBOutlet var imgView: UIImageView!
    
}







6.放入兩張測試用圖片

7.ViewController.swift
import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{

    let photoCount = 2 //照片張數
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoCount
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        //取得cell
        let cell: Cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! Cell
        print("indexPath:\(indexPath.row)")
        if indexPath.row == 0{
            cell.imgView.image = UIImage(named: "p1.jpg") // 放入第一張
        }else{
            cell.imgView.image = UIImage(named: "p2.jpg") // 放入第二張
        }
        
        return cell
    }

}


檔案下載:
https://github.com/terryyamg/PhotosGalleryTest
參考來源:
https://github.com/TDAbboud/PhotosGalleryApp
http://www.brianjcoleman.com/tutorial-collection-view-using-swift/

沒有留言 :

張貼留言