Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to UIView autolayout methods which are to be deprecated

According to the UIView.h header file, the methods below are to be deprecated.

What is the alternative way of working with autolayout in code?

I don't see how the methods recommended in the code comment replace their existing counterparts as they work on the actual constraint and not on the relation between the UIView and the constraint.

@interface UIView (UIConstraintBasedLayoutInstallingConstraints)

- (NSArray *)constraints NS_AVAILABLE_IOS(6_0);

- (void)addConstraint:(NSLayoutConstraint *)constraint NS_AVAILABLE_IOS(6_0); // This method will be deprecated in a future release and should be avoided.  Instead, set NSLayoutConstraint's active property to YES.
- (void)addConstraints:(NSArray *)constraints NS_AVAILABLE_IOS(6_0); // This method will be deprecated in a future release and should be avoided.  Instead use +[NSLayoutConstraint activateConstraints:].
- (void)removeConstraint:(NSLayoutConstraint *)constraint NS_AVAILABLE_IOS(6_0); // This method will be deprecated in a future release and should be avoided.  Instead set NSLayoutConstraint's active property to NO.
- (void)removeConstraints:(NSArray *)constraints NS_AVAILABLE_IOS(6_0); // This method will be deprecated in a future release and should be avoided.  Instead use +[NSLayoutConstraint deactivateConstraints:].
@end
like image 696
LK__ Avatar asked Apr 28 '15 06:04

LK__


1 Answers

The constraints themselves contain the relation (that is, they point to the view or views involved in the relation), so the old way of adding the constraints to a view was redundant and sometimes confusing because you had to choose the right view in the hierarchy to add them to.

In the new way, you just create the constraints and set their active property to YES (for Objective-C) or to true (for Swift) and the system adds it to the correct view for you. If you have more than one constraint to add, you call the class method activateConstraints: and it sets the property for you.

With the old method, it was up to the programmer to add the constraints to the correct view. If you had a constraint the involved view A and view B, then there are 3 possibilities of where to add the constraint:

  1. If view A is a subview of view B (or a subview of a subview), then the constraint should be added to view B.
  2. If view B is a subview of view A (or a subview of a subview), then the constraint should be added to view A.
  3. If view A and view B are both subviews of another view (call it C), then the constraint should be added to view C.

With the new method, you just set the constraint's active property to YES/true and the system figures this out for you. It's much easier.

like image 143
vacawama Avatar answered Oct 25 '22 06:10

vacawama