简体   繁体   中英

ConvertRect doesn't work as expected

I'm trying to convert deep 'Subview' frame to an upper 'UIView'. I'm attaching the view hierarchy here.

Attaching illustration:

在此处输入图像描述

I've tried this, but the result are way off screen:

let rect = smallSubview.convert(smallSubview.frame, to: bigSuperview)

I'm trying to convert the small 'Subview' frame, to 'VideoCrop'/bigSuperView coordinate space. Any suggestions? Thank you!

Not sure, but shouldn't you be considering bounds rather than frame of your smallSubView ??

I mean :

let rect = smallSubview.convert(smallSubview.bounds, to: bigSuperview)

EDIT

I could not have answered your comment in answer hence updating my answer :)

The quick view of convert API suggests

func convert(_ rect: CGRect, to view: UIView?) -> CGRect Description
Converts a rectangle from the receiver's coordinate system to that of another view.

Parameters

rect A rectangle specified in the local coordinate system (bounds) of the receiver.

view The view that is the target of the conversion operation. If view is nil, this method instead converts to window base coordinates. Otherwise, both view and the receiver must belong to the same UIWindow object.

As it suggests you should be considering bounds rather than frame :)

Whats the difference between frame and bounds then ??

Bounds : Specifies the views location and size of view in its own coordinate system. Frame: While this specifies the location and size of view in its superViews coordinate system :)

Hence bounds of any view will have its origin as (0,0) where as frame has its x and y with respect to its superview :) while height and width being same :)

Apple's convert#to is really silly.

One way to understand it:

Say you want a view named "echo" to be exactly where you are.

echo.frame = convert(bounds, to: echo.superview!)

is exactly the same as:

echo.frame = superview!.convert(frame, to: echo.superview!)

It's like...

convert(bounds

means essentially "your frame in your superview", and that's exactly the same as

superview!.convert(frame

which also means "your frame in your superview"

You can always do either of these two things, they're identical:

convert(bounds ...

superview!.convert(frame ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM