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

很多項目中用都會有相冊功能,實現相冊中瀏覽的圖片的功能,你可能會想到使用 scrollview ,但我更建議你通過復用機制來實現 . 這里基于 UICollection View來實現,當然你也可以通過 UITableView 來實現.具體看代碼:

class BigImageView: UIView,UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate {
  
  var downloadSucBlock:(()->())?
  var downloadFailBlock:(()->())?
  var dataArray:[String] = []{ //數據源數組
    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() {
    //創建 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)
    //注冊 cell
    collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollectionCell")
    
    //創建索引 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)
    
    //創建下載按鈕
    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
  /**
   創建橫向滾動視圖(建議寫在 UIView 的類別中)
   
   - parameter itemSize:      cell 的大小
   - parameter sectionInset:   cell 上下左右的間距
   
   - returns: UICollectionView
   */
  func createHorizontalCollectionView(itemSize:CGSize,sectionInset:UIEdgeInsets)-> UICollectionView {
    //創建布局對象
    let layout = UICollectionViewFlowLayout()
    //設置 cell 的大小
    layout.itemSize = itemSize
    //設置 cell 上下左右的間距
    layout.sectionInset = sectionInset
    //設置橫向豎線的最小值
    layout.minimumLineSpacing = sectionInset.left
    //設置滾動方向
    layout.scrollDirection = .Horizontal
    //創建網格視圖
    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 數組
   - parameter selCount: 點擊的圖片索引
   */
  func showBigImageView(imageArr:[String],selCount:Int) {
    if imageArr.count == 0 {
      return
    }
    dataArray = imageArr
    //滾動到指定位置
    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()
  }
}

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容