Swift之相册浏览效果的实现

swift-相册浏览.gif

今天给大家分享一个简单的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!)
    //初始化布局,创建layout,必须设置
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = UICollectionViewScrollDirection.Vertical
    //设置垂直方向得最小距离
    layout.minimumInteritemSpacing = 10
    //设置水平方向得最小距离
    layout.minimumLineSpacing = 10
    
    //创建collectionView,并添加layout,必须添加
    self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
    self.view.addSubview(collectionView!)
    //设置背景颜色
    self.collectionView?.backgroundColor = UIColor.whiteColor()
    
    //签署代理和数据源
    self.collectionView?.delegate = self
    self.collectionView?.dataSource = self
    //注册单元格
    self.collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "newCell")
}
//设置单元格的个数,在collectionView称其为item
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return dataArray!.count;
}
//创建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;
}
//代理方法事项单元格得大小,单元格显示的大小
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);
}
//点击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来实现点击图片的显示
import UIKit


class ActiviPhotoViewController: UIViewController {

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

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "个人图片"
    let jumCollection = JumCollection(frame: self.view.bounds)
    jumCollection.backgroundColor = UIColor.whiteColor()
    
    //传图片内容
    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来实现图片的展示
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()
    
    //创建图片视图
    imageView = UIImageView(frame:self.contentView.frame)
    imageView?.contentMode = .ScaleAspectFit
    scroll?.addSubview(imageView!)
    imageView?.userInteractionEnabled = true
    
    //设置代理
    scroll?.delegate = self
    //设置方法倍数
    scroll?.minimumZoomScale = 1.0
    scroll?.maximumZoomScale = 2.0
    self.addSubview(scroll!)
}
//代理方法 返回一个放大缩小的视图
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    return imageView;
}
//添加手势
func hand() {
    let tapGes = UITapGestureRecognizer(target: self, action: #selector(JumCollectionViewCell.tapAction(_:)))
    tapGes.numberOfTapsRequired = 1   //设置点击次数
    tapGes.numberOfTouchesRequired = 1   //设置触摸点
    imageView?.addGestureRecognizer(tapGes)
    
    let tapGes1 = UITapGestureRecognizer(target: self, action: #selector(JumCollectionViewCell.tapAction(_:)))
    tapGes1.numberOfTapsRequired = 2   //设置点击次数
    tapGes1.numberOfTouchesRequired = 1   //设置触摸点
    imageView?.addGestureRecognizer(tapGes1)

}
func tapAction(tap:UITapGestureRecognizer) {
    switch tap.numberOfTapsRequired {
    case 1:
        //点击一次隐藏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() {
    //获取点击视图
    let bar = self.viewController()!.navigationController!.navigationBar
    let isHidden = !bar.hidden
    self.viewController()!.navigationController?.setNavigationBarHidden(isHidden, animated: true)
}
//scroll恢复原样
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()
    //设置滚动方向
    flowLayout.scrollDirection = .Horizontal
    //设置垂直方向得最小距离
    flowLayout.minimumInteritemSpacing = 0
    //设置水平方向得最小距离
    flowLayout.minimumLineSpacing = 0
    //设置四周得边缘距离
    //初始化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!)
}

//创建item得个数
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array!.count;
}
//创建item得内容
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
    
}
//代理方法事项单元格得大小
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进行扩展
import UIKit

extension UIView {
func viewController() -> UIViewController? {
    //通过响应者链,取得此视图所在的视图控制器
    var next = self.nextResponder()

    while(next != nil) {
        //判断响应者对象是否是视图控制器类型
        if next!.isKindOfClass(UIViewController.self) {
            return next as? UIViewController;
        }
        next = next!.nextResponder()
    }
    return nil;
}
}

大家如果想下载代码,请加群:512847147,让我们一起快乐的学习swift吧(o)。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 78,535评论 1 171
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 26,654评论 1 143
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 30,058评论 0 102
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 16,578评论 0 87
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 21,835评论 0 144
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 17,936评论 0 87
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 10,714评论 2 161
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 10,149评论 0 78
  • 想象着我的养父在大火中拼命挣扎,窒息,最后皮肤化为焦炭。我心中就已经是抑制不住地欢快,这就叫做以其人之道,还治其人...
    爱写小说的胖达阅读 8,667评论 5 112
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 11,938评论 0 130
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 10,675评论 1 125
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 11,478评论 0 128
  • 白月光回国,霸总把我这个替身辞退。还一脸阴沉的警告我。[不要出现在思思面前, 不然我有一百种方法让你生不如死。]我...
    爱写小说的胖达阅读 6,331评论 0 17
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 9,135评论 2 116
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 12,252评论 3 124
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 7,971评论 0 3
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 8,186评论 0 77
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 12,725评论 2 133
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 13,357评论 2 130

推荐阅读更多精彩内容