Determine if UIView is visible to the user?

前端 未结 12 1804
不知归路
不知归路 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 16:06

    The solution that worked for me was to first check if the view has a window, then to iterate over superviews and check if:

    1. the view is not hidden.
    2. the view is within its superviews bounds.

    Seems to work well so far.

    Swift 3.0

    public func isVisible(view: UIView) -> Bool {
    
      if view.window == nil {
        return false
      }
    
      var currentView: UIView = view
      while let superview = currentView.superview {
    
        if (superview.bounds).intersects(currentView.frame) == false {
          return false;
        }
    
        if currentView.isHidden {
          return false
        }
    
        currentView = superview
      }
    
      return true
    }
    

提交回复
热议问题