• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 

 

 

核心代码

 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

    }
}

  


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Swift-解析XML格式数据(分别使用GDataXML和DDXML)发布时间:2022-07-13
下一篇:
swift-计算器(斯坦福公开课)发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap