How to change label constraints during runtime?

后端 未结 4 1797
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 13:18

I have a table view and a cell inside it. The cell contains three labels: header label and two labels below one to each other. Sometimes, I need to hide those two labels bel

4条回答
  •  生来不讨喜
    2020-12-07 14:00

    Put the labels you want to hide into a view, once everything has the correct layout constraints, add a height constraint to the container view, 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.

    @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.

提交回复
热议问题