【问题标题】:Set UIView bottom space constraint to keyboard height将 UIView 底部空间约束设置为键盘高度
【发布时间】:2015-08-05 16:44:40
【问题描述】:

我是自动布局的忠实粉丝,但一直在 Storyboard 中实现它。

我有一个 UIView,我希望底部空间约束位于键盘结束的位置。

我已经定义了所有的约束,有人可以告诉我如何在代码中为底部空间实现这个约束吗?以及如何根据特定的 iDevice 获取键盘高度的值并将其与约束匹配。

谢谢

【问题讨论】:

标签: xcode autolayout


【解决方案1】:

像这样取出视图的底部约束

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

并使用它

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupKeyboard:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self setupKeyboard:NO];
}

- (void)setupKeyboard:(BOOL)appearing
{
    if (appearing) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }else{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    }
}

- (void)keyboardWillShow:(NSNotification*)notification
{
    CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    double duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int curve = [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    [UIView beginAnimations:@"keyboardShown" context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:curve];

    self.constraintContainerBottom.constant = keyboardSize.height;
    [self.view layoutIfNeeded];

    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification*)notification
{
    double duration = [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int curve = [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    [UIView beginAnimations:@"keyboardHidden" context:nil];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:curve];

    self.constraintContainerBottom.constant = 0;
    [self.view layoutIfNeeded];

    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

【讨论】:

  • "constraint" 不是 NSLayoutConstraint IBOutlet 的属性...?
  • @nickjf89 这取决于您的处理方式。它的解决方案很好。 :) 我认为这是工作。
  • 它实际上是不变的......我已经更新了答案。
  • 对不起,如果我很笨...如何设置 IBOutlet 以限制我的 UIView?
  • 只需双击约束,然后在左侧窗格中将选择一个约束。只需将其拖到所需的类文件并设置名称即可。
猜你喜欢
  • 2013-08-25
  • 2015-02-27
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2016-03-01
  • 2020-06-28
  • 2020-08-27
  • 1970-01-01
相关资源
最近更新 更多