UIKeyboard avoidance and Auto Layout

后端 未结 6 846
梦谈多话
梦谈多话 2021-01-31 09:16

Given the focus on Auto Layout in iOS 6, and the recommendation by Apple engineers (see WWDC 2012 videos) that we no longer manipulate a views\' frame directly, how wou

6条回答
  •  半阙折子戏
    2021-01-31 09:58

    I created a view like this that would watch the keyboard and change its own constraints when the keyboard comes on/off the screen.

    @interface YMKeyboardLayoutHelperView ()
    @property (nonatomic) CGFloat desiredHeight;
    @property (nonatomic) CGFloat duration;
    @end
    
    @implementation YMKeyboardLayoutHelperView
    
    - (id)init
    {
        self = [super init];
        if (self) {
            self.translatesAutoresizingMaskIntoConstraints = NO;
    
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:@"UIKeyboardWillShowNotification" object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:@"UIKeyboardWillHideNotification" object:nil];
        }
        return self;
    }
    
    - (void)keyboardWillShow:(NSNotification *)notification
    {
        // Save the height of keyboard and animation duration
        NSDictionary *userInfo = [notification userInfo];
        CGRect keyboardRect = [userInfo[@"UIKeyboardBoundsUserInfoKey"] CGRectValue];
        self.desiredHeight = CGRectGetHeight(keyboardRect);
        self.duration = [userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    
        [self setNeedsUpdateConstraints];
    }
    
    - (void)keyboardWillHide:(NSNotification *)notification
    {
        // Reset the desired height (keep the duration)
        self.desiredHeight = 0.0f;
    
        [self setNeedsUpdateConstraints];
    }
    
    - (void)updateConstraints
    {
        [super updateConstraints];
    
        // Remove old constraints
        if ([self.constraints count]) {
            [self removeConstraints:self.constraints];
        }
    
        // Add new constraint with desired height
        NSString *constraintFormat = [NSString stringWithFormat:@"V:[self(%f)]", self.desiredHeight];
        [self addVisualConstraints:constraintFormat views:@{@"self": self}];
    
        // Animate transition
        [UIView animateWithDuration:self.duration animations:^{
            [self.superview layoutIfNeeded];
        }];
    
    }
    
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
    @end
    

提交回复
热议问题