iOS仿微信的懸浮窗實(shí)現(xiàn),自定義轉(zhuǎn)場(chǎng)動(dòng)畫(huà),使用超級(jí)簡(jiǎn)單

先看看效果圖

screenshot1.gif
screenshot2.gif

demo在這里。

代碼結(jié)構(gòu)

代碼結(jié)構(gòu).jpg
  • HXSuspendViewManager是一個(gè)單例,負(fù)責(zé)主要的邏輯,控制懸浮窗和扇形view的生命周期、展示和隱藏。
  • HXSuspendViewController是一個(gè)協(xié)議,只要你的控制器遵守了這個(gè)協(xié)議,你的控制器就可以添加到懸浮窗中。
  • UINavigationController+HXSuspend是UINavigationController的分類,懸浮窗相關(guān)的處理邏輯都在這里。
  • HXCircleTransition是自定義轉(zhuǎn)場(chǎng)動(dòng)畫(huà)類
  • HXSuspendWindow懸浮窗的視圖,繼承自UIWindow
  • HXCircularSectorView右下角的扇形view

實(shí)現(xiàn)原理

  • 攔截UINavigationController的右滑返回手勢(shì),判斷是否顯示右下角的扇形view,主要包括三個(gè)方法,這三個(gè)方法都通過(guò)runtime交換了方法實(shí)現(xiàn)
    open override func viewDidLoad() {
        super.viewDidLoad()
        UINavigationController.initializeSuspendOnce()
        interactivePopGestureRecognizer?.delegate = self
        delegate = self
    }
    
    private static let onceToken = UUID().uuidString
    private static func initializeSuspendOnce() {
        guard self == UINavigationController.self else { return }
        DispatchQueue.hx_once(onceToken) {
            let needSwizzleSelectorArr = [
                NSSelectorFromString("_updateInteractiveTransition:"),
                NSSelectorFromString("_finishInteractiveTransition:transitionContext:"),
                NSSelectorFromString("_cancelInteractiveTransition:transitionContext:"),
                NSSelectorFromString("popViewControllerAnimated:"),
                NSSelectorFromString("popToRootViewControllerAnimated:"),
                NSSelectorFromString("popToViewController:animated:")
            ]
            for selector in needSwizzleSelectorArr {
                let newSelector = ("hx_" + selector.description).replacingOccurrences(of: "__", with: "_")
                let originalMethod = class_getInstanceMethod(self, selector)
                let swizzledMethod = class_getInstanceMethod(self, Selector(newSelector))
                if originalMethod != nil && swizzledMethod != nil {
                    method_exchangeImplementations(originalMethod!, swizzledMethod!)
                }
            }
        }
    }

滑動(dòng)中:hx_updateInteractiveTransition:
滑動(dòng)結(jié)束,并完成pop:hx_finishInteractiveTransition:transitionContext:
滑動(dòng)結(jié)束,取消了pop:hx_cancelInteractiveTransition:transitionContext:
具體實(shí)現(xiàn)如下:

     @objc func hx_updateInteractiveTransition(_ percentComplete: CGFloat) {
        hx_updateInteractiveTransition(percentComplete)
        guard let poppingVC = hx_poppingVC as? HXSuspendViewController,
            let keyWindow = UIApplication.shared.keyWindow,
            let point = interactivePopGestureRecognizer?.location(in: keyWindow) else { return }
        /// 添加右下角扇形view
        if HXSuspendViewManager.shared.circularSectorView.superview == nil {
            keyWindow.addSubview(HXSuspendViewManager.shared.circularSectorView)
        }
        /// 如果是新的控制器,顯示扇形,否則顯示懸浮窗
        if poppingVC.suspendIdentifier != HXSuspendViewManager.shared.suspendWindow?.viewContoller?.suspendIdentifier {
            HXSuspendViewManager.shared.circularSectorView.type = .add
            HXSuspendViewManager.shared.circularSectorView.show(percent: percentComplete)
            HXSuspendViewManager.shared.circularSectorView.move(point: point)
        } else {
            HXSuspendViewManager.shared.changeSuspendViewAlpha(percentComplete, animated: false)
        }
    }
    
    @objc func hx_finishInteractiveTransition(_ percentComplete: CGFloat, transitionContext: UIViewControllerContextTransitioning)  {
        hx_finishInteractiveTransition(percentComplete, transitionContext: transitionContext)
        /// 保證最后一定調(diào)用隱藏扇形view
        defer {
            HXSuspendViewManager.shared.circularSectorView.hide()
        }
        guard let poppingVC = hx_poppingVC as? HXSuspendViewController,
            let keyWindow = UIApplication.shared.keyWindow,
            let point = interactivePopGestureRecognizer?.location(in: keyWindow) else { return }
        if poppingVC.suspendIdentifier != HXSuspendViewManager.shared.suspendWindow?.viewContoller?.suspendIdentifier {
            /// 添加新的懸浮窗
            if HXSuspendViewManager.shared.circularSectorView.isPointInView(point: point) {
                HXSuspendViewManager.shared.addSuspendView(viewController: poppingVC, percent: percentComplete)
            }
        } else {
            // 播放一個(gè)假的轉(zhuǎn)場(chǎng)動(dòng)畫(huà)
            HXSuspendViewManager.shared.fakeTransitionAnimation(percentComplete)
        }
    }
    
    @objc func hx_cancelInteractiveTransition(_ percentComplete: CGFloat, transitionContext: UIViewControllerContextTransitioning) {
        hx_cancelInteractiveTransition(percentComplete, transitionContext: transitionContext)
        defer {
            HXSuspendViewManager.shared.circularSectorView.hide()
        }
        guard let poppingVC = hx_poppingVC as? HXSuspendViewController else { return }
        if poppingVC.suspendIdentifier == HXSuspendViewManager.shared.suspendWindow?.viewContoller?.suspendIdentifier  {
            HXSuspendViewManager.shared.changeSuspendViewAlpha(0, animated: false)
        } else {
            HXSuspendViewManager.shared.changeSuspendViewAlpha(1, animated: false)
        }
    }
  • 實(shí)現(xiàn)自定義的轉(zhuǎn)場(chǎng)動(dòng)畫(huà),通過(guò)UINavigationControllerDelegate代理實(shí)現(xiàn)
// MARK: -  UINavigationControllerDelegate
extension UINavigationController: UINavigationControllerDelegate {
    
    public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        hx_poppingVC = nil
    }
    
    public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        guard let suspendWindow = HXSuspendViewManager.shared.suspendWindow,
            let currentSuspendVC = suspendWindow.viewContoller else { return nil }
        switch operation {
        case .push:
            // 保證是suspendWindow所持有的viewController
            guard let suspendToVC = toVC as? HXSuspendViewController,
                suspendToVC.suspendIdentifier == currentSuspendVC.suspendIdentifier else { return nil }
            return HXCircleTransition(operationType: .push, originPoint: suspendWindow.center)
        case .pop:
            guard let suspendFromVC = fromVC as? HXSuspendViewController,
                suspendFromVC.suspendIdentifier == currentSuspendVC.suspendIdentifier else { return nil }
            return HXCircleTransition(operationType: .pop, originPoint: suspendWindow.center)
        default:
            return nil
        }
    }
    
}

其他細(xì)節(jié)

  • 懸浮窗的拖動(dòng)處理
     @objc private func didPan(gesture: UIPanGestureRecognizer) {
        let point = gesture.location(in: UIApplication.shared.keyWindow)
        switch gesture.state {
        case .began:
            panStartPoint = point
            panStartCenter = center
            HXSuspendViewManager.shared.circularSectorView.type = .delete
            HXSuspendViewManager.shared.circularSectorView.show()
        case .changed:
            let panDeltaX = point.x - panStartPoint.x
            let panDeltaY = point.y - panStartPoint.y
            let centerX = min(max(panStartCenter.x + panDeltaX, bounds.width / 2), hx_screenWidth - bounds.width / 2)
            let centerY = min(max(panStartCenter.y + panDeltaY, bounds.height / 2), hx_screenHeight - bounds.height / 2 )
            center = CGPoint(x: centerX, y: centerY)
            HXSuspendViewManager.shared.circularSectorView.move(point: center)
        default:
            if HXSuspendViewManager.shared.circularSectorView.isPointInView(point: center) {
                HXSuspendViewManager.shared.removeSuspendView()
            } else {
                // 保證懸浮窗在安全范圍之內(nèi)
                let centerX = min(max(center.x, bounds.width / 2 + 10), hx_screenWidth - bounds.width / 2 - 10)
                let centerY = min(max(center.y, bounds.height / 2 + hx_statusBarHeight), hx_screenHeight - bounds.height / 2 - hx_safeBottomHeight)
                UIView.animate(withDuration: 0.2) {
                    self.center = CGPoint(x: centerX, y: centerY)
                }
            }
            HXSuspendViewManager.shared.circularSectorView.hide()
        }
    }
  • 轉(zhuǎn)場(chǎng)動(dòng)畫(huà)的具體實(shí)現(xiàn),pop的實(shí)現(xiàn)同理
    private func pushAnimation(transitionContext: UIViewControllerContextTransitioning) {
        guard let fromVC = transitionContext.viewController(forKey: .from),
            let toVC = transitionContext.viewController(forKey: .to) else {
                completeTransition(transitionContext: transitionContext)
                HXSuspendViewManager.shared.changeSuspendViewAlpha(0, animated: false)
                return
        }
        // 添加到containerView中
        let containerView = transitionContext.containerView
        containerView.addSubview(fromVC.view)
        containerView.addSubview(toVC.view)
        // 計(jì)算path
        let originSize = HXSuspendViewConfig.suspendViewSize
        let originFrame = CGRect(x: originPoint.x - originSize.width / 2, y: originPoint.y - originSize.height / 2, width: originSize.width, height: originSize.height)
        let beginPath = UIBezierPath(ovalIn: originFrame)
        let finalRadius = HXCircleTransition.radius(with: originPoint)
        let finalPath = UIBezierPath(ovalIn: originFrame.insetBy(dx: -finalRadius, dy: -finalRadius))
        let maskLayer = CAShapeLayer()
        maskLayer.path = finalPath.cgPath
        toVC.view.layer.mask = maskLayer
        // 開(kāi)始動(dòng)畫(huà)
        let animation = CABasicAnimation(keyPath: "path")
        animation.fromValue = beginPath.cgPath
        animation.toValue = finalPath.cgPath
        animation.duration = transitionDuration(using: transitionContext)
        animation.delegate = self
        maskLayer.add(animation, forKey: "path")
        // 改變懸浮窗alpha
        HXSuspendViewManager.shared.changeSuspendViewAlpha(0, animated: true)
    }

使用方法

超級(jí)簡(jiǎn)單的使用方法,完全無(wú)侵入。


class VipcnViewController: UIViewController, HXSuspendViewController {
    
    // MARK: -  HXSuspendViewController
    var suspendIdentifier: Int {
        // 保證suspendIdentifier唯一
        return hashValue
    }
    
    var suspendIcon: UIImage? {
        return UIImage(named: "2")
    }

}

就是這么簡(jiǎn)單,只需要讓你的控制器遵守HXSuspendViewController協(xié)議就行了。

總結(jié)

iOS仿微信的懸浮窗,自定義轉(zhuǎn)場(chǎng)動(dòng)畫(huà),集成超級(jí)簡(jiǎn)單。
如果覺(jué)得對(duì)你有幫助,請(qǐng)給個(gè)star,demo在這里。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容