swift - scrollview 判断左右移动, 以及上下两个view联动

 

 

 

核心代码

 1.

 

2.

 

3.

 

 

界面代码VFL 

/* 浏览作品view*/

import UIKit

/**
 *  图片浏览器(大图和缩略图)
 */
class JYBrowseWorksView: UIView {
    
    
    /// 数据源参数(外界传入)
    var dataArray:[WorkImagesProtocol] = [] {
        didSet{
            self.topCollectionView.reloadData()
            self.bottomCollectionView.reloadData()
            if dataArray.isEmpty {
                self.topCollectionView.backgroundView = self.emptyView
                bottomCollectHeight?.constant = 0
                self.topCollectionView.backgroundColor = UIColor(hexColor: "F9F9F9")
            }else{
                self.topCollectionView.backgroundView = nil
                 bottomCollectHeight?.constant = 70
                self.topCollectionView.backgroundColor = UIColor.white
            }
        }
    }
    /// 照片比例类型(默认1:1)
    var photoSizeType: JYMyCenterPhotoHeightType = .squareType {
        didSet{
            self.collectionHeightConstraint?.constant = photoSizeType.photoHeight
            if photoSizeType == .rectangleType {
                self.collectionMegrainConstraint?.constant = 72
            }else {
                self.collectionMegrainConstraint?.constant = 24
            }
        }
    }
    /// 当前显示的图片索引
    private var selectIndex:Int = 0 {
        didSet{
            self.reloadCollectionUI()
        }
    }
    /// 空页面
    private let emptyView = JYZDEmptyView(emptyAreement: JYEmptyViewStruct(emptyType: .noImageEmptyType, offsetY: -70, titleTipStr: "暂无作品", buttonTitleStr: nil))
    /// 底部相册的高度约束
    private var bottomCollectHeight: NSLayoutConstraint?
    /// 可分页滑动collectionView
    private lazy var topCollectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: JY_DEVICE_WIDTH, height: self.photoSizeType.photoHeight)
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.backgroundColor = UIColor.white
        collectionView.isPagingEnabled = true
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    /// 可选择点中的collectionview
    private var bottomCollectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 70, height: 70)
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.backgroundColor = UIColor.white
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    /// topcollectionView 开始滑动时的位移
    private var startContentOffsetX : CGFloat = 0
    
    /// topcollectionView 将要停止滑动时的位移
    private var willEndContentOffsetX : CGFloat = 0
    
    /// 控制高度的约束
    private var collectionHeightConstraint: NSLayoutConstraint?
    /// 控制距离的约束
    private var collectionMegrainConstraint: NSLayoutConstraint?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.translatesAutoresizingMaskIntoConstraints = false
        self.configerUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 刷新collectionview的UI
    private func reloadCollectionUI() {
        
        let endContentOffsetX = topCollectionView.contentOffset.x
        if endContentOffsetX < willEndContentOffsetX , willEndContentOffsetX < startContentOffsetX {
            DDLOG(message: "左移")
            if !bottomCollectionView.indexPathsForVisibleItems.contains(IndexPath(item: selectIndex, section: 0)) {
                bottomCollectionView.selectItem(at: IndexPath(item: selectIndex, section: 0), animated: true, scrollPosition: UICollectionView.ScrollPosition.left)
            }
        } else if endContentOffsetX > willEndContentOffsetX , willEndContentOffsetX > startContentOffsetX {
            DDLOG(message: "右移")
            if !bottomCollectionView.indexPathsForVisibleItems.contains(IndexPath(item: selectIndex, section: 0)) {
                bottomCollectionView.selectItem(at: IndexPath(item: selectIndex, section: 0), animated: true, scrollPosition: UICollectionView.ScrollPosition.right)
            }
        }
        self.bottomCollectionView.reloadData()
    }
}

// MARK: - UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
extension JYBrowseWorksView : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "JYBrowseWorksCollectionCell", for: indexPath) as! JYBrowseWorksCollectionCell
        cell.configerCellData(imageData: dataArray[indexPath.row])
        if collectionView == bottomCollectionView {
            let select = selectIndex == indexPath.row ? true : false
            cell.configerSelectCell(isSelect: select)
        }else {
//            cell.imageView.contentMode = .scaleAspectFit
//            cell.clipsToBounds = false
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        if collectionView == topCollectionView {
            return 0.0001
        }
        return 10
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        if collectionView == topCollectionView {
            return 0
        }
        return 10
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if collectionView == topCollectionView {
            return UIEdgeInsets.zero
        }
        return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if collectionView == bottomCollectionView {
            selectIndex = indexPath.row
            topCollectionView.scrollToItem(at: IndexPath(item: indexPath.row, section: 0), at: UICollectionView.ScrollPosition.left, animated: true)
        }
    }
    
    /// 滑动顶部collectionview,底部collectionview显示顶部当前显示的图片
    ///
    /// - Parameter scrollView: scrollView description
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView == topCollectionView {
            let x = scrollView.contentOffset.x
            let i:Int = Int(x/UIScreen.main.bounds.size.width)
            self.selectIndex = i
        }
    }
    
    /// 获取将要滑动时位移
    /// 用于判断滑动方向
    /// - Parameter scrollView: scrollView description
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        if scrollView == topCollectionView {
            startContentOffsetX = scrollView.contentOffset.x
        }
    }
    
    /// 获取将要结束时 topCollectionView 的位移
    ///  用于判断 滑动方向
    /// - Parameters:
    ///   - scrollView: scrollView description
    ///   - velocity: velocity description
    ///   - targetContentOffset: targetContentOffset description
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        if scrollView == topCollectionView {
            willEndContentOffsetX = scrollView.contentOffset.x
        }
    }
}

// MARK: - UI布局
extension JYBrowseWorksView {
    
    private func configerUI() {
        
        topCollectionView.delegate = self
        topCollectionView.dataSource  = self
        bottomCollectionView.delegate = self
        bottomCollectionView.dataSource = self
        
        topCollectionView.register(JYBrowseWorksCollectionCell.classForCoder(), forCellWithReuseIdentifier: "JYBrowseWorksCollectionCell")
        bottomCollectionView.register(JYBrowseWorksCollectionCell.classForCoder(), forCellWithReuseIdentifier: "JYBrowseWorksCollectionCell")

        self.addSubview(topCollectionView)
        self.addSubview(bottomCollectionView)
        
        let vd:[String:UIView] = ["topCollectionView":topCollectionView,"bottomCollectionView":bottomCollectionView]
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[topCollectionView]|", options: [], metrics: nil, views: vd))
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[bottomCollectionView]|", options: [], metrics: nil, views: vd))
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[topCollectionView]", options: [], metrics: nil, views: vd))
        self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[bottomCollectionView]|", options: [], metrics: nil, views: vd))
        self.collectionHeightConstraint = topCollectionView.heightAnchor.constraint(equalToConstant: JY_DEVICE_WIDTH)
        self.collectionHeightConstraint?.isActive = true
        self.collectionMegrainConstraint = bottomCollectionView.topAnchor.constraint(equalTo: topCollectionView.bottomAnchor, constant: 24)
        self.collectionMegrainConstraint?.isActive = true
        bottomCollectHeight = bottomCollectionView.heightAnchor.constraint(equalToConstant: 70)
        bottomCollectHeight?.isActive = true

    }
}

  

转载于:https://www.cnblogs.com/qingzZ/p/10276011.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值