How to handle relative positioning in iOS automatically?

I want to place sub UIView (sub_UIView) as a subset of the parent UIView (parent_UIView). When parent_UIView resizes / moves, sub_UIView will remain relative position of parent_UIView. For example, sub_UIView is in the lower right corner of parent_UIView. When move_UIView moves, sub_UIView will be in the bottom right corner of parent_UIView automatically.

I managed to do this manually by updating the sub_UIView frame when the parent_UIView frame moves, but how to do it automatically in iOS? are there any properties for this? (similar to autoresizingmask for resizing objects)

Thanks!

+6
source share
1 answer

Updated old answer that only shows masks for resizing

Autostart (iOS 6)

In iOS 6, autostart was added, albeit rather ugly, to work with Xcode in the / xib storyboard. Autolayout is too big to explain, but the gist of it is that it is a set of rules between views in a hierarchy. This way you can snap the x position to the right border of the parent view. See Auto Layout Programming Guide

Auto Resist Masks (iOS 2)

Take a look at the options in the Size Inspector:

Autoresizing and positioning inside a view

This is equivalent to doing

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

Please note that there is a difference between executing code and executing it through IB. IB auto-implementation parameters for borders work like racks, for example, choosing the right one means that "my right border is now attached to the right border of the supervisor."

On the other hand, the code does the opposite, where you need to indicate which boundaries are not set, aka. they are flexible. Height and width work fine.

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

If everything fails, don’t start doing manual positioning everywhere, I was in that position, and it just leads to an unmaintanable, spaghetti code, where three or more methods tinker with the same kind of properties.

Instead, prefer to do all your custom positioning on UIView -layoutSubviews . This method is called as necessary when setNeedsLayout triggered, for example, when changing the width of the view, subviews receive a subviews layout event. In addition, greatly simplify the implementation of rotating interfaces, since this method is called for the new width to determine how the animation will look.

Keep in mind that layout representations are executed after layout or makeup masks have been completed.

+4
source

Source: https://habr.com/ru/post/896236/


All Articles