I have a UILabel positioned on the screen with aut

2019-09-20 16:32发布

问题:

This question already has an answer here:

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

Project: http://cl.ly/1T2K0V3w1P21

It's best seen through the project, it's a small download stripped down to just the view controller.

Basically, my UILabel stays in place perfectly with auto layout, but when I hide the navigation bar (you can do this in the project by tapping the screen anywhere) it causes it to twitch. How do I make it so it stays in the exact same position regardless of what's going on with the navigation bar?

It seems that it being animated (which I want) causes AutoLayout to get confused.

Here's what the constraints on the label look like:

Could anyone offer some advice as to what I'm doing wrong?

回答1:

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;
}