swiftxcodesafeareaviewsafearea

Can't get view maxX without safe area


I'm trying to get the maxX of a view for calculations but although the view is inside a stack view (with others views) and the constraints are to not inside the safe area (and it's appear like that as well) when I’m doing

self.frame.maxX

on my view, It’s giving me view maxX + safe area x.. (I checked it)

Does anyone know why and have any solution ?

--------------

Edit:

Thanks to @Sweeper I understand my mistake and what I need:

self.bounds.maxX

This one gives the right maxX.

---------------

Thanks, David


Solution

  • Assuming that the view is actually displayed on the screen, you can apply the view's safeAreaInsets to the view's bounds, then convert the resulting rectangle to the superview's coordinate space, which is the coordinate space of frame.

    let safeBounds = someView.bounds.inset(by: someView.safeAreaInsets)
    let safeFrame = someView.superview?.convert(safeBounds, from: someView)
    let maxX = safeFrame?.maxX
    

    From the docs:

    The safe area of a view reflects the area not covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. You obtain the safe area for a view by applying the insets in this property to the view's bounds rectangle.