Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically reposition UIButton as subview of UIImageView when rotating

I'm working on an iPad app that lets you control different things in a prototype of an intelligent house. For example it lets you turn lights on and off. For this, I have made a UIImageView that shows the floor plan of the house and added UIButtons as subviews for each lamp that can be toggled.

enter image description here

As you can see the buttons are placed perfectly on the floor plan using the setFrame method of each UIButton. However, when I rotate the iPad to portrait orientation, the following happens:

enter image description here

The buttons obviously still have the same origin, however it is not relative to the repositioning of the image.

The floor plan image has the following settings for struts and springs:

enter image description here

and has its content mode set to Aspect Fit.

My question is

how do I dynamically reposition each UIButton, such that it has the same relative position. I figure I have to handle this in the {did/should}AutorotateToInterfaceOrientation delegate method.

It should be noted that the UIImageView is zoomable and to handle this I have implemented the scrollViewDidZoom delegate method as follows:

for (UIView *button in _floorPlanImage.subviews) {       
    CGRect oldFrame = button.frame;
    [button.layer setAnchorPoint:CGPointMake(0.5, 1)];
    button.frame = oldFrame;
    button.transform = CGAffineTransformMakeScale(1.0/scrollView.zoomScale, 1.0/scrollView.zoomScale);
}

Thank you in advance!

like image 243
Zappel Avatar asked Nov 14 '22 03:11

Zappel


1 Answers

I find the best way to layout subviews is in the - (void) layoutSubviews method. You will have to subclass your UIImageView and override the method.

This method will automatically get called whenever your frame changes and also gets called the first time your view gets presented.

If you put all your layout code in this method, it prevents layout fragmentation and repetition, keeps your view code in your views, and most things just work by default.

like image 196
cobbal Avatar answered Apr 08 '23 17:04

cobbal