AutoLayout with hidden UIViews?

后端 未结 13 1379
南方客
南方客 2020-11-27 09:27

I feel like it\'s a fairly common paradigm to show/hide UIViews, most often UILabels, depending on business logic. My question is, what is the best

13条回答
  •  一整个雨季
    2020-11-27 10:07

    The best practice is, once everything has the correct layout constraints, add a height or with constraint, depending how you want the surrounding views to move and connect the constraint into an IBOutlet property.

    Make sure that your properties are strong

    in code yo just have to set the constant to 0 and activate it, tho hide the content, or deactivate it to show the content. This is better than messing up with the constant value an saving-restoring it. Do not forget to call layoutIfNeeded afterwards.

    If the content to be hidden is grouped, the best practice is to put all into a view and add the constraints to that view

    @property (strong, nonatomic) IBOutlet UIView *myContainer;
    @property (strong, nonatomic) IBOutlet NSLayoutConstraint *myContainerHeight; //should be strong!!
    

    -(void) showContainer
    {
        self.myContainerHeight.active = NO;
        self.myContainer.hidden = NO;
        [self.view layoutIfNeeded];
    }
    -(void) hideContainer
    {
        self.myContainerHeight.active = YES;
        self.myContainerHeight.constant = 0.0f;
        self.myContainer.hidden = YES;
        [self.view layoutIfNeeded];
    }
    

    Once you have your setup you can test it in IntefaceBuilder by setting your constraint to 0 and then back to the original value. Don't forget to check other constraints priorities so when hidden there is no conflict at all. other way to test it is to put it to 0 and set the priority to 0, but, you should not forget to restore it to the highest priority again.

提交回复
热议问题