Determine if UIView is visible to the user?

前端 未结 12 1793
不知归路
不知归路 2020-12-07 15:21

is it possible to determine whether my UIView is visible to the user or not?

My View is added as subview several times into a Tab Bar

12条回答
  •  执笔经年
    2020-12-07 15:58

    Tested solution.

    func isVisible(_ view: UIView) -> Bool {
        if view.isHidden || view.superview == nil {
            return false
        }
    
        if let rootViewController = UIApplication.shared.keyWindow?.rootViewController,
            let rootView = rootViewController.view {
    
            let viewFrame = view.convert(view.bounds, to: rootView)
    
            let topSafeArea: CGFloat
            let bottomSafeArea: CGFloat
    
            if #available(iOS 11.0, *) {
                topSafeArea = rootView.safeAreaInsets.top
                bottomSafeArea = rootView.safeAreaInsets.bottom
            } else {
                topSafeArea = rootViewController.topLayoutGuide.length
                bottomSafeArea = rootViewController.bottomLayoutGuide.length
            }
    
            return viewFrame.minX >= 0 &&
                   viewFrame.maxX <= rootView.bounds.width &&
                   viewFrame.minY >= topSafeArea &&
                   viewFrame.maxY <= rootView.bounds.height - bottomSafeArea
        }
    
        return false
    }
    

提交回复
热议问题