美文网首页花落√莫相思
66-Swift之旋转菜单(UICollectionView)

66-Swift之旋转菜单(UICollectionView)

作者: NetWork小贱 | 来源:发表于2017-09-01 15:46 被阅读26次

    一 、 旋转菜单的需要的知识点

    • 重写 UICollectionView 的布局类UICollectionViewLayout

    • 重写UICollectionView 的触摸方法。

    • 余弦定理

    二 、 详细方法的介绍和展示

    1、 重写 UICollectionView 的布局类需要重写下面几个方法

    • override func prepare() :: 初始化 Items 的函数。初始化之前先调用父类的该方法(super.prepare())。

    • override func layoutAttributesForElements(in rect: CGRect) :: 返回 Items 的所有 UICollectionViewLayoutAttributes 对象。

    • override var collectionViewContentSize: CGSize :: 设置UICollectionView 的视图范围。

    1> ** prepare()** 的函数重写
    override func prepare() {
        super.prepare()
        // TODO: 获取圆盘上Item的个数
        let itemCount = self.collectionView?.numberOfItems(inSection: 0)
        // TODO: 获取圆盘的半径(获取CollectionView的宽和高的最小的一个)
        let diskRadii = min((self.collectionView?.bounds.width)!, (self.collectionView?.bounds.height)!) * 0.5
        // TODO: 计算圆盘的圆心
        let diskCenterPoint = CGPoint.init(x: (self.collectionView?.bounds.width)! * 0.5, y: (self.collectionView?.bounds.height)! * 0.5)
        // TODO: 检测CollectionVie的总高度是否小于默认的ItemRadii高度
        ItemRadii = diskRadii > 40 ? ItemRadii:diskRadii
        // TODO: 计算每一个Item的位置和大小
        for i in 0..<itemCount! {
            // TODO: 获取每个Item系统的 LayoutAttribute
            let layoutAttribute = UICollectionViewLayoutAttributes.init(forCellWith: IndexPath.init(row: i, section: 0))
            // TODO: 设置大小
            layoutAttribute.size = CGSize.init(width: ItemRadii * 2, height: ItemRadii * 2)
            // TODO: 计算Item中心距离圆盘的中心距离
            let disDiff = diskRadii - ItemRadii
            // TODO: 计算每个Items的中心位置
            let itemCenterX = diskCenterPoint.x + cos(CGFloat(2 * .pi/CGFloat(itemCount!) * CGFloat(i))+rotationAngle) * disDiff
            let itemCenterY = diskCenterPoint.y + sin(2 * .pi / CGFloat(itemCount!) * CGFloat(i)+rotationAngle) * disDiff
            // TODO: 设置Item的中心
            layoutAttribute.center = CGPoint.init(x: itemCenterX, y: itemCenterY)
            // TODO: 存储Item的layoutAttributes
            LayoutAttributes.add(layoutAttribute)
        }
    }
    
    2> layoutAttributesForElements(in rect: CGRect) 函数的重写
    // MARK: Item的layoutAttribute属性的返回
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
         return (LayoutAttributes as! [UICollectionViewLayoutAttributes])
    }
    
    3> collectionViewContentSize: CGSize 函数的重写
    // MARK: 设置圆盘的大小
    override var collectionViewContentSize: CGSize {
        get {
            return (self.collectionView?.frame.size)!
        }
        set {
            self.collectionViewContentSize = newValue
        }
    }
    

    2、 重写UICollectionView 的触摸方法

    在重写UICollectionView 的触摸方法时,由于Swift 对 UICollectionView 对类的扩展需要使用到 OC ,还要桥接文件。本简书就使用继承来解决这个问题。我们要重写的UICollectionView触摸的方法如下:

    • func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
      通过该方法,你可以限制触摸的范围,最重要的是记录开始触摸的一点。
    • func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
      触摸后手势的移动,处理圆盘的转动。这里需要注意:有一个角度的计算。使用到的知识就是 三角函数的 余弦定理
    1> touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 的函数的重写
    // MARK: 设置触摸起始点
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        // 获取触摸的点
        let touchPoint = touches.first?.location(in: self)
        lastPoint = touchPoint!
    }
    
    2> **func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) **的重写函数
    // MARK: 移动旋转处理
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let discCenter = CGPoint.init(x: self.bounds.width * 0.5, y: self.bounds.height * 0.5)
        // 获取触摸的点
        let touchPoint = touches.first?.location(in: self)
        // 计算滑动的角度
        let rads = self.computingAngle(startPoint1: lastPoint, endPoint1: touchPoint!, discCenter: discCenter)
        totalRads += rads
        let FlowLayout = self.collectionViewLayout as! RotatingMenuViewLayout
        FlowLayout.rotationAngle = totalRads * rotationRate
        // CollectionView重新布局
        FlowLayout.invalidateLayout()
        // 更新最后的一点
        lastPoint = touchPoint!
    }
    
    3> 角度计算函数
    // MARK: 计算移动的角度
    func computingAngle(startPoint1:CGPoint,endPoint1:CGPoint,discCenter:CGPoint) -> CGFloat {
        // 计算开始点和结束点距离中心点的长度
        let a =  startPoint1.x - discCenter.x
        let b =  startPoint1.y - discCenter.y
        let c =  endPoint1.x - discCenter.x
        let d =  endPoint1.y - discCenter.y
        // 使用余弦定理
        let shang =  a*c + b*d
        let yu = sqrt(a * a + b * b) * sqrt(c*c + d*d)
        // 使用反余弦求得角度
        let rads = acos( Double(shang) / Double(yu))
        var plusminus = -1
        if (endPoint1.x - startPoint1.x < 0 && d > 0)  {
            plusminus = 1
        }else if endPoint1.y - startPoint1.y < 0 && a < 0 {
            plusminus = 1
        }else if endPoint1.x - startPoint1.x > 0 && d < 0 {
            plusminus = 1
        }else if endPoint1.y - startPoint1.y > 0 && a > 0 {
            plusminus = 1
        }else if endPoint1.x - startPoint1.x > 0 && d > 0 {
            plusminus = -1
        }else if a > 0 && endPoint1.y - startPoint1.y < 0 {
            plusminus = -1
        }else if endPoint1.x - startPoint1.x < 0 && d < 0 {
            plusminus = -1
        } else if  endPoint1.y - startPoint1.y > 0 && a < 0{
            plusminus = -1
        }
        // 转化成角度
        return  CGFloat(rads) *  CGFloat(plusminus)
    }
    

    这里有带优化,目前也是最接近完美的一种方法处理圆盘的旋转方向避免不要的卡顿。

    三 、 旋转菜单的创建

    1> 创建UICollectionView 对象。

    // MARK: 创建UICollectionView
    func createCollectionView() {
        let FlowLayout = RotatingMenuViewLayout.init()
        FlowLayout.ItemRadii = 40
        FlowLayout.rotationAngle = .pi
        let CollectionView = RotatingMenuCollectionView.init(frame: CGRect.init(x: 0, y: 100, width: view.bounds.width, height: 400), collectionViewLayout: FlowLayout)
        CollectionView.delegate = self
        CollectionView.dataSource = self
        self.view.addSubview(CollectionView)
        CollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "NetWork小贱")
        // 添加中图片
        let centerImageV = UIImageView.init(frame: CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: CollectionView.bounds.height - 240, height: CollectionView.bounds.height - 240)))
        centerImageV.center = CGPoint.init(x: CollectionView.bounds.width * 0.5, y: CollectionView.bounds.height * 0.5)
        centerImageV.image = UIImage.init(named: "taiji.png")
        centerImageV.contentMode = .scaleAspectFill
        CollectionView.addSubview(centerImageV)
        
    }
    

    2> 代理方法的实现

    // MARK: 代理
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return (dataArray?.count)!
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let Cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NetWork小贱", for: indexPath)
        Cell.contentView.backgroundColor = UIColor.red
        Cell.contentView.layer.cornerRadius = Cell.contentView.bounds.width * 0.5
        // 添加标记
        Cell.tag = indexPath.row
        // 添加一个手势
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(itemDidSelecd(_ :)))
        Cell.addGestureRecognizer(tap)
        
        // 标记
        for item in Cell.contentView.subviews {
            item.removeFromSuperview()
        }
        let markL = UILabel.init(frame: Cell.bounds)
        markL.text = dataArray![indexPath.row]
        markL.font = UIFont.boldSystemFont(ofSize: 30)
        markL.textAlignment = .center
        Cell.contentView.addSubview(markL)
        return Cell
    }
    
    // 由于Cell的点击触发事件
    func itemDidSelecd(_ tap:UITapGestureRecognizer)  {
        let AlertV = UIAlertController.init(title: nil, message: dataArray![(tap.view?.tag)!], preferredStyle: .alert)
        let sureAction = UIAlertAction.init(title: "确定", style: .cancel, handler: nil)
        AlertV.addAction(sureAction)
        self.present(AlertV, animated: true, completion: nil)
    }
    

    五、最终的效果展示

    4.gif

    相关文章

      网友评论

        本文标题:66-Swift之旋转菜单(UICollectionView)

        本文链接:https://www.haomeiwen.com/subject/laxkjxtx.html