Using AutoLayout, how do I keep a UILabel in the same place when the navigation bar disappears?

前端 未结 3 649
萌比男神i
萌比男神i 2021-01-03 13:59

I have a view controller with a UILabel in it that prints some words when a button is tapped. When the button is tapped, the navigation bar is set to hidden.

So I t

3条回答
  •  孤城傲影
    2021-01-03 14:47

    (Copying my answer from the question you posted that is marked as duplicate: I have a UILabel positioned on the screen with autolayout, but when I hide the navigation bar it causes the label to "twitch" for a second)

    Instead of bottom space constraint, you can try to define the top space constraint to the superview from the label (which is 22 in the constant), connect it as an IBOutlet to your view property, and animate it when the navigation bar is hidden or shown.

    For example, I declare the top space property as topSpaceConstraint:

    @property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpaceConstraint;
    

    Then inside the hideControls method, I can animate the constraint:

    - (void)hideControls:(BOOL)visible {
        if (visible) {
            [UIView animateWithDuration:UINavigationControllerHideShowBarDuration animations:^{
                self.topSpaceConstraint.constant = 66; //44 is the navigation bar height, you need to find a way not to hardcode this
                [self.view layoutIfNeeded];
            }];     
        }
        else {
            [UIView animateWithDuration:UINavigationControllerHideShowBarDuration animations:^{
                self.topSpaceConstraint.constant = 22;
                [self.view layoutIfNeeded];
            }];
        }
        [self.navigationController setNavigationBarHidden:visible animated:YES];
        self.backFiftyWordsButton.hidden = visible;
        self.forwardFiftyWordsButton.hidden = visible;
        self.WPMLabel.hidden = visible;
        self.timeRemainingLabel.hidden = visible;
    }
    

提交回复
热议问题