Since XCode made them available, Storyboards became a key concept for almost any GUI-oriented app: there's nothing wrong about it - there isn't a better way to design & arrange your views, objects and your whole UI in timely fashion. Expecially if you properly learn to use the Storyboard constraints, which are a powerful way to place your items around and ensure they'll stay in their place.
Nonetheless, there could be situations where you need to programmatically remove the Storyboard-defined constraints: for example, if you need to change an item position right after an user interaction.
In order to handle such scenarios I wrote the following static method:
1 2 3 |
+ (void)RemoveContraintsFromView:(UIView*)view removeParentConstraints:(bool)parent removeChildConstraints:(bool)child; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
+ (void)RemoveContraintsFromView:(UIView *)view removeParentConstraints:(bool)parent removeChildConstraints:(bool)child { if (parent) { // Remove constraints between view and its parent. UIView *superview = view.superview; [view removeFromSuperview]; [superview addSubview:view]; } if (child) { // Remove constraints between view and its children. [view removeConstraints:[view constraints]]; } } |
You can throw it in any helper class you already have or create another one (mine is called LayoutHelper): once you did that, you can use it in the following way:
1 2 3 |
[self.myView RemoveContraintsFromView removeParentConstraints:true removeChildConstraints:true]; |
As you might see you can configure it to remove ancestor and/or children constraints. Needles to say, either self.myView and their parent / children can be items of any UIView derived class (UIButton, UIImage, UILabel, etc.).
Keep in mind that, once you removed the Storyboard-defined constraints, you can also programmatically add new ones using the method explained here.
Happy coding!
2 Comments on “Objective C: removing UIStoryboard constraints programmatically”