Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view work

I've been using that kind of methods on and off but never really understood how they behaved.

Every time I try to use them, I find myself poking in the dark as I try different aspect and it never seem to do what I expect it to.

For the sake of argument, I'm trying to convert the frame I get from UIKeyboard's notification.

In landscape mode, I get this NSRect:

UIKeyboardFrameEndUserInfoKey = NSRect: {{406, 0}, {362, 1024}}

Now I want to convert it to the proper rect (swap x/y, width and height) so I do

CGRect compatibleRect = [self convertRect:[[[notif userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue] toView:nil];

But the rect becomes:

compatibleRect = CGRect: {{406,406}, {362, 1024}}

Any help would be appreciated :)

like image 806
Pier-Olivier Thibault Avatar asked Aug 01 '10 14:08

Pier-Olivier Thibault


1 Answers

You are using it wrong. It basically does a coordinate conversion. I'm assuming it starts by converting the rect from the starting view to window coordinates and then converting back from window coordinates to the coordinate system of the second view. Here's an example.

You have two subviews in your window, one with a frame of {{25,0}, {100, 100}}, The other with a frame of {{50, 50}, {200, 200}} You want to translate the following rect {{50, 50}, {50, 50}} from the first subview to the second subview. Here's how it might work.

  1. convert the rect from the first subview's coordinated to window coordinates: Since the subview we are starting from has an origin of {25,0} we need to translate it to window coordinates. This can be done by adding the origin of the subview to the origin of the rect, so the new rect in window coordinates is {{75, 50}, {50, 50}}

  2. convert the new rect from window coordinates to the second subview's coordinates: We start with the rect {{75, 50}, {50, 50}}, The frame of the second subview is {{50, 50}, {200, 200}}. Now we subtract the origin of the second subview to the rect to do our translation. So we end up with a translated rect of {{25, 0}, {50, 50}}

like image 66
Elfred Avatar answered Oct 14 '22 14:10

Elfred