Swift之相冊瀏覽效果的實(shí)現(xiàn)

swift-相冊瀏覽.gif

今天給大家分享一個(gè)簡單的swift版的相冊瀏覽的小demo,如有不足澡绩,請大家指教(o)肺稀。

首先,在ViewController中的代碼:
import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

var collectionView : UICollectionView?
var dataArray : [String]?
var imageView : UIImageView?

override func viewDidLoad() {
    super.viewDidLoad()
    self.dataArray = [String]()
    for i in 1..<12 {
        let imageStr = String.init(format: "aion%02d.jpg", i)
        dataArray?.append(imageStr)
    }
    print(dataArray!)
    //初始化布局酌毡,創(chuàng)建layout,必須設(shè)置
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = UICollectionViewScrollDirection.Vertical
    //設(shè)置垂直方向得最小距離
    layout.minimumInteritemSpacing = 10
    //設(shè)置水平方向得最小距離
    layout.minimumLineSpacing = 10
    
    //創(chuàng)建collectionView蕾管,并添加layout枷踏,必須添加
    self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
    self.view.addSubview(collectionView!)
    //設(shè)置背景顏色
    self.collectionView?.backgroundColor = UIColor.whiteColor()
    
    //簽署代理和數(shù)據(jù)源
    self.collectionView?.delegate = self
    self.collectionView?.dataSource = self
    //注冊單元格
    self.collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "newCell")
}
//設(shè)置單元格的個(gè)數(shù),在collectionView稱其為item
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return dataArray!.count;
}
//創(chuàng)建cell
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("newCell", forIndexPath: indexPath)
    self.imageView = UIImageView(frame: cell.bounds)
    cell.contentView.addSubview(imageView!)
    
    self.imageView!.image = UIImage(named: dataArray![indexPath.item])
    if self.imageView!.image == nil {
        self.imageView!.image = UIImage(named: "aion01.jpg")
    }

    return cell;
}
//代理方法事項(xiàng)單元格得大小,單元格顯示的大小
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSizeMake(self.view.bounds.size.width/4-10, self.view.bounds.size.height/4-20);
}
//點(diǎn)擊item
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    let photoVC = ActiviPhotoViewController()
    photoVC.imageArray = self.dataArray
    photoVC.currentIndex = indexPath.item
    self.navigationController?.pushViewController(photoVC, animated: true)
    
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}
自定義ActiviPhotoViewController來實(shí)現(xiàn)點(diǎn)擊圖片的顯示
import UIKit


class ActiviPhotoViewController: UIViewController {

var imageArray : [String]?
var currentIndex : NSInteger?

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "個(gè)人圖片"
    let jumCollection = JumCollection(frame: self.view.bounds)
    jumCollection.backgroundColor = UIColor.whiteColor()
    
    //傳圖片內(nèi)容
    jumCollection.array = self.imageArray
    jumCollection.getIndex(self.currentIndex!)
    self.view.addSubview(jumCollection)
 
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationController?.navigationBar.hidden = false
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}
自定義JumCollectionViewCell來實(shí)現(xiàn)圖片的展示
import UIKit

class JumCollectionViewCell: UICollectionViewCell,UIScrollViewDelegate {

var index : NSInteger?
var scroll : UIScrollView?
var imageView : UIImageView?

override init(frame: CGRect) {
    super.init(frame: frame)
    
    self.scrollView()
    self.hand()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func scrollView() -> Void {
    scroll = UIScrollView(frame: self.contentView.bounds)
    scroll?.backgroundColor = UIColor.whiteColor()
    
    //創(chuàng)建圖片視圖
    imageView = UIImageView(frame:self.contentView.frame)
    imageView?.contentMode = .ScaleAspectFit
    scroll?.addSubview(imageView!)
    imageView?.userInteractionEnabled = true
    
    //設(shè)置代理
    scroll?.delegate = self
    //設(shè)置方法倍數(shù)
    scroll?.minimumZoomScale = 1.0
    scroll?.maximumZoomScale = 2.0
    self.addSubview(scroll!)
}
//代理方法 返回一個(gè)放大縮小的視圖
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    return imageView;
}
//添加手勢
func hand() {
    let tapGes = UITapGestureRecognizer(target: self, action: #selector(JumCollectionViewCell.tapAction(_:)))
    tapGes.numberOfTapsRequired = 1   //設(shè)置點(diǎn)擊次數(shù)
    tapGes.numberOfTouchesRequired = 1   //設(shè)置觸摸點(diǎn)
    imageView?.addGestureRecognizer(tapGes)
    
    let tapGes1 = UITapGestureRecognizer(target: self, action: #selector(JumCollectionViewCell.tapAction(_:)))
    tapGes1.numberOfTapsRequired = 2   //設(shè)置點(diǎn)擊次數(shù)
    tapGes1.numberOfTouchesRequired = 1   //設(shè)置觸摸點(diǎn)
    imageView?.addGestureRecognizer(tapGes1)

}
func tapAction(tap:UITapGestureRecognizer) {
    switch tap.numberOfTapsRequired {
    case 1:
        //點(diǎn)擊一次隱藏navBar
        self.hiddenBar()
        break;
    case 2:
        if scroll?.zoomScale == 1.0 {
            scroll?.setZoomScale(2.0, animated: true)
        }else if scroll?.zoomScale == 2.0 {
            scroll?.setZoomScale(1.0, animated: true)
        }
        break;
    default:
        break;
    }
}
func hiddenBar() {
    //獲取點(diǎn)擊視圖
    let bar = self.viewController()!.navigationController!.navigationBar
    let isHidden = !bar.hidden
    self.viewController()!.navigationController?.setNavigationBarHidden(isHidden, animated: true)
}
//scroll恢復(fù)原樣
func bringView() {
    scroll?.setZoomScale(1.0, animated: true)
}

}
自定義JumCollection
import UIKit

class JumCollection: UICollectionView,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

var currentIndex : NSInteger?
var array : [String]?

override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
    
    array = [String]()
    
    //初始化布局類掰曾,uicollectiongViewLayout得子類
    let flowLayout = UICollectionViewFlowLayout()
    //設(shè)置滾動(dòng)方向
    flowLayout.scrollDirection = .Horizontal
    //設(shè)置垂直方向得最小距離
    flowLayout.minimumInteritemSpacing = 0
    //設(shè)置水平方向得最小距離
    flowLayout.minimumLineSpacing = 0
    //設(shè)置四周得邊緣距離
    //初始化collectionView
    super.init(frame: frame, collectionViewLayout: flowLayout)
    self.delegate = self
    self.dataSource = self
    self.pagingEnabled = true
    
    
    //注冊單元格
    self.registerClass(JumCollectionViewCell.self, forCellWithReuseIdentifier: "new")
    self.showsVerticalScrollIndicator = false
    self.showsHorizontalScrollIndicator = false

}
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func getIndex(index: NSInteger) {
    self.currentIndex = index
    self.contentOffset = CGPointMake(self.frame.size.width*CGFloat(self.currentIndex!), self.contentOffset.y)
    print(self.currentIndex!)
}

//創(chuàng)建item得個(gè)數(shù)
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array!.count;
}
//創(chuàng)建item得內(nèi)容
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("new", forIndexPath: indexPath) as! JumCollectionViewCell
    
    cell.imageView?.image = UIImage(named: array![indexPath.item])
    
    return cell
    
}
//代理方法事項(xiàng)單元格得大小
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSizeMake(self.bounds.size.width,self.bounds.size.height);
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    JumCollectionViewCell().bringView()
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
    // Drawing code
}
*/

}
對UIView進(jìn)行擴(kuò)展
import UIKit

extension UIView {
func viewController() -> UIViewController? {
    //通過響應(yīng)者鏈旭蠕,取得此視圖所在的視圖控制器
    var next = self.nextResponder()

    while(next != nil) {
        //判斷響應(yīng)者對象是否是視圖控制器類型
        if next!.isKindOfClass(UIViewController.self) {
            return next as? UIViewController;
        }
        next = next!.nextResponder()
    }
    return nil;
}
}

大家如果想下載代碼,請加群:512847147,讓我們一起快樂的學(xué)習(xí)swift吧(o)掏熬。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末佑稠,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子旗芬,更是在濱河造成了極大的恐慌舌胶,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件疮丛,死亡現(xiàn)場離奇詭異幔嫂,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)这刷,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進(jìn)店門婉烟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人暇屋,你說我怎么就攤上這事似袁。” “怎么了咐刨?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長而涉。 經(jīng)常有香客問我联予,道長,這世上最難降的妖魔是什么季眷? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任子刮,我火速辦了婚禮窑睁,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘担钮。我一直安慰自己,他們只是感情好病线,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布送挑。 她就那樣靜靜地躺著暖眼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪诫肠。 梳的紋絲不亂的頭發(fā)上栋豫,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天丧鸯,我揣著相機(jī)與錄音,去河邊找鬼丛肢。 笑死蜂怎,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的氢伟。 我是一名探鬼主播幽歼,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼猪勇!你這毒婦竟也來了泣刹?” 一聲冷哼從身側(cè)響起犀被,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤寡键,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后员舵,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年措近,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瞭郑。...
    茶點(diǎn)故事閱讀 40,498評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡屈张,死狀恐怖苇本,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情笛厦,我是刑警寧澤俺夕,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布劝贸,位于F島的核電站,受9級特大地震影響映九,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜捌议,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一瓣颅、第九天 我趴在偏房一處隱蔽的房頂上張望譬正。 院中可真熱鬧檬姥,春花似錦粉怕、人聲如沸斋荞。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至幸逆,卻和暖如春还绘,著一層夾襖步出監(jiān)牢的瞬間栖袋,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工昔案, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留踏揣,地道東北人捞稿。 一個(gè)月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓拼缝,卻偏偏與公主長得像,于是被迫代替她去往敵國和親铃辖。 傳聞我的和親對象是個(gè)殘疾皇子猪叙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容