Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle relative positioning in iOS automatically?

Tags:

ios

subview

I want to position a sub UIView (sub_UIView) as a subview of parent UIView (parent_UIView). When the parent_UIView resizing/moving, the sub_UIView would stay the relative position of the parent_UIView. For example, the sub_UIView is at the bottom right corner of the parent_UIView. When the parent_UIView is moving, the sub_UIView would stay at the bottom right corner of the parent_UIView automatically.

I managed to do this manually by updating the frame of the sub_UIView when the parent_UIView's frame moving, but how to do this automatically in iOS? are there any properties for this? (similar to autoresizingmask for resizing subviews)

like image 986
androidkc Avatar asked Aug 30 '11 18:08

androidkc


1 Answers

Updated old response, that only mentioned resizing masks

Autolayout (iOS 6)

In iOS 6, autolayout was added, albeit, kinda ugly to work with XCode in a storyboard/xib. Autolayout is way too big to explain, but the essence of it, is that it's a set of rules between views within the hierarchy. Thus, you can stick the x position of a view to the right border of a parent view. See the Auto Layout Programming Guide

Autoresizing Masks (iOS 2)

Take a look at the options in the Size Inspector:

Autoresizing and positioning inside a view

This is the equivalent of doing

myView.autoresizingMask = UIViewAutoresizingMaskFlexibleTopMargin | 
    UIViewAutoresizingMaskFlexibleLeftMargin | 
    UIViewAutoresizingMaskFlexibleWidth | 
    UIViewAutoresizingMaskFlexibleHeight;

Notice that there's a difference between doing it by code and doing it through IB. The IB autoresizing settings for the borders work as struts, selecting the right one, for example, means, "my right border is now stuck to the superview's right border".

On the other hand, code does the opposite, where you need to specify which borders are not strut-ed, aka. they are flexible. Height and Width works normally.

Layout Subviews (iOS 2, but gotchas for iOS5+)

If everything fails, don't start doing manual positioning all over the place, I've been in that position, and it just leads to unmaintanable, spaghetti code, where three or more methods are messing with the same view properties.

Instead, prefer to do all your custom positioning on UIView -layoutSubviews. This method gets called as needed when a setNeedsLayout has been triggered, for example, when the width a view changes, the subviews get the layout subviews event. Also makes implementing rotating interfaces much easier, since this method gets called for the new width, to determine how the animation will look like.

Keep in mind that layout subviews works after Auto Layout/Auto-resizing masks have been performed.

like image 78
Can Avatar answered Nov 11 '22 12:11

Can