swift UICollectionView 的使用:圖片瀏覽視圖

很多項(xiàng)目中用都會(huì)有相冊(cè)功能,實(shí)現(xiàn)相冊(cè)中瀏覽的圖片的功能,你可能會(huì)想到使用 scrollview ,但我更建議你通過(guò)復(fù)用機(jī)制來(lái)實(shí)現(xiàn) . 這里基于 UICollection View來(lái)實(shí)現(xiàn),當(dāng)然你也可以通過(guò) UITableView 來(lái)實(shí)現(xiàn).具體看代碼:

class BigImageView: UIView,UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate {
  
  var downloadSucBlock:(()->())?
  var downloadFailBlock:(()->())?
  var dataArray:[String] = []{ //數(shù)據(jù)源數(shù)組
    didSet{
      collectionView.reloadData()
    }
  }
  //
  var collectionView:UICollectionView!
  var indexLabel:UILabel!
  var downBtn:UIButton!
  var curIndex = 0
  var curImage :UIImage?
  
  // MARK: - system method
  override func awakeFromNib() {
    super.awakeFromNib()
    self.setUp()
  }
  override init(frame: CGRect) {
    super.init(frame: frame)
    self.setUp()
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  // MARK: - private method
  private func setUp() {
    //創(chuàng)建 collectionView
    collectionView = self.createHorizontalCollectionView(CGSizeMake(SCREEN_WIDTH, self.frame.height), sectionInset: UIEdgeInsetsZero)
    collectionView.backgroundColor = UIColor.blackColor()
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.pagingEnabled = true
    self.addSubview(collectionView)
    //注冊(cè) cell
    collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionCell")
    
    //創(chuàng)建索引 label
    let pointX = (SCREEN_WIDTH-100)/2.0
    indexLabel = UILabel.init(frame: CGRectMake(pointX, SCREEN_HEIGHT-40, 100, 20))
    indexLabel.textColor = UIColor.whiteColor()
    indexLabel.font = UIFont.systemFontOfSize(15)
    indexLabel.textAlignment = .Center
    self.addSubview(indexLabel)
    
    //創(chuàng)建下載按鈕
    downBtn = UIButton.init(type: .Custom)
    downBtn.frame = CGRectMake(SCREEN_WIDTH - 45, SCREEN_HEIGHT - 45, 25, 25)
    downBtn.setImage(UIImage.init(named: "down_image"), forState: .Normal)
    downBtn.addTarget(self, action: #selector(downBtnAction), forControlEvents: .TouchUpInside)
    self.addSubview(downBtn)
  }
  func downBtnAction() {
    //下載圖片到本地
    if let curImage = curImage {
      UIImageWriteToSavedPhotosAlbum(curImage, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
  }
  func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject){
    if let didFinishSavingWithError = didFinishSavingWithError {
      print(didFinishSavingWithError)
      if let downloadFailBlock = downloadFailBlock {
        downloadFailBlock()
      }
    }else{
      if let downloadSucBlock = downloadSucBlock {
        downloadSucBlock()
      }
    }
  }
  func removeSelf()  {
    self.removeFromSuperview()
  }
  func getNewFrame(frame:CGRect) -> CGRect {
    if  frame.width/SCREEN_WIDTH != frame.height/SCREEN_HEIGHT{
      let newH = SCREEN_WIDTH*frame.height/frame.width
      let newPointY = (SCREEN_HEIGHT-newH)/2.0
      if frame.width/SCREEN_WIDTH > frame.height/SCREEN_HEIGHT {
        return CGRectMake(0, newPointY, SCREEN_WIDTH, newH)
      }else{
        return CGRectMake(0, 0, SCREEN_WIDTH, newH)
      }
      
    }else{
      return CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
    }
  }
  // MARK: - public method
  /**
   創(chuàng)建橫向滾動(dòng)視圖(建議寫(xiě)在 UIView 的類(lèi)別中)
   
   - parameter itemSize:      cell 的大小
   - parameter sectionInset:   cell 上下左右的間距
   
   - returns: UICollectionView
   */
  func createHorizontalCollectionView(itemSize:CGSize,sectionInset:UIEdgeInsets)-> UICollectionView {
    //創(chuàng)建布局對(duì)象
    let layout = UICollectionViewFlowLayout()
    //設(shè)置 cell 的大小
    layout.itemSize = itemSize
    //設(shè)置 cell 上下左右的間距
    layout.sectionInset = sectionInset
    //設(shè)置橫向豎線的最小值
    layout.minimumLineSpacing = sectionInset.left
    //設(shè)置滾動(dòng)方向
    layout.scrollDirection = .Horizontal
    //創(chuàng)建網(wǎng)格視圖
    let collectionView = UICollectionView.init(frame: CGRectMake(0, 0, SCREEN_WIDTH, self.frame.height), collectionViewLayout: layout)
    collectionView.scrollsToTop = false
    collectionView.backgroundColor = UIColor.whiteColor()
    return collectionView
  }
  /**
   展示圖片瀏覽圖
   
   - parameter imageArr: 圖片 URL 數(shù)組
   - parameter selCount: 點(diǎn)擊的圖片索引
   */
  func showBigImageView(imageArr:[String],selCount:Int) {
    if imageArr.count == 0 {
      return
    }
    dataArray = imageArr
    //滾動(dòng)到指定位置
    collectionView.scrollToItemAtIndexPath(NSIndexPath.init(forItem: selCount, inSection: 0), atScrollPosition: .Right, animated: false)
  }
  // MARK: - UICollectionViewDelegate
  func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return dataArray.count
  }
  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath)
    cell.backgroundColor = UIColor.blackColor()
    for subview in cell.subviews {
      subview.removeFromSuperview()
    }
    let image =  UIImage.init(named: "ICON108")
    curImage = image
    let imageView = UIImageView.init(image:image)
    imageView.userInteractionEnabled = true
    let newFrame = self.getNewFrame(imageView.frame)
    imageView.frame = newFrame
    if  newFrame.height > SCREEN_HEIGHT{
      let scrollView = UIScrollView.init(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
      scrollView.addSubview(imageView)
      scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, newFrame.height)
      cell.addSubview(scrollView)
      let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(removeFromSuperview))
      imageView.addGestureRecognizer(tapGesture)
    }else{
      cell.addSubview(imageView)
    }
    indexLabel.text = String(format: "%ld / %ld",indexPath.row+1,dataArray.count)
    return cell
  }
  func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    self.removeSelf()
  }
}

期待你的評(píng)論建議O(∩_∩)O~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末较木,一起剝皮案震驚了整個(gè)濱河市炒瘸,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌纳账,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,188評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件妹孙,死亡現(xiàn)場(chǎng)離奇詭異倦炒,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)刁卜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)志电,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人蛔趴,你說(shuō)我怎么就攤上這事挑辆。” “怎么了孝情?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,562評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵鱼蝉,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我箫荡,道長(zhǎng)魁亦,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,893評(píng)論 1 295
  • 正文 為了忘掉前任羔挡,我火速辦了婚禮洁奈,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘绞灼。我一直安慰自己利术,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布低矮。 她就那樣靜靜地躺著印叁,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上喉钢,一...
    開(kāi)封第一講書(shū)人閱讀 51,708評(píng)論 1 305
  • 那天姆打,我揣著相機(jī)與錄音,去河邊找鬼肠虽。 笑死幔戏,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的税课。 我是一名探鬼主播闲延,決...
    沈念sama閱讀 40,430評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼韩玩!你這毒婦竟也來(lái)了垒玲?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,342評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤找颓,失蹤者是張志新(化名)和其女友劉穎合愈,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體击狮,經(jīng)...
    沈念sama閱讀 45,801評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡佛析,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了彪蓬。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片寸莫。...
    茶點(diǎn)故事閱讀 40,115評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖档冬,靈堂內(nèi)的尸體忽然破棺而出膘茎,到底是詐尸還是另有隱情,我是刑警寧澤酷誓,帶...
    沈念sama閱讀 35,804評(píng)論 5 346
  • 正文 年R本政府宣布披坏,位于F島的核電站,受9級(jí)特大地震影響呛牲,放射性物質(zhì)發(fā)生泄漏刮萌。R本人自食惡果不足惜驮配,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評(píng)論 3 331
  • 文/蒙蒙 一娘扩、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧壮锻,春花似錦琐旁、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,008評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至掰邢,卻和暖如春牺陶,著一層夾襖步出監(jiān)牢的瞬間伟阔,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,135評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工掰伸, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留皱炉,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,365評(píng)論 3 373
  • 正文 我出身青樓狮鸭,卻偏偏與公主長(zhǎng)得像合搅,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子歧蕉,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評(píng)論 2 355

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