2015-01-01 2 views
0

Я создаю элемент управления комментариями для приложения. Этот элемент управления состоит из UITextView, встроенного в UIView. Все ограничения обрабатываются программно. Что происходит, когда пользователь удаляет UITextView, клавиатура откроется. Это вызывает методы наблюдения за клавиатурой, и затем я корректирую нижнее ограничение для элемента управления ввода комментария, чтобы двигаться вверх с помощью клавиатуры. Тем не менее, я также пытаюсь увеличить высоту управления вводом в то же время, чтобы у пользователя было больше места для ввода. У меня проблемы с этим.UIView программное ограничение увеличения высоты при наличии клавиатуры

-(void)updateViewConstraints 
{ 

    NSDictionary *views = @{ 
          @"table"   : self.commentsTableView, 
          @"seeMoreComments" : self.seeMoreCommentsView, 
          @"commentInput" : self.commentEntryInput 
          }; 

    //See More Comments Constraints 
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[seeMoreComments]-0-|" options:0 metrics:nil views:views]]; 
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[seeMoreComments(45)]" options:0 metrics:nil views:views]]; 

    //Table view constraints 
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[table]-0-|" options:0 metrics:nil views:views]]; 
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[seeMoreComments]-0-[table]-0-|" options:0 metrics:nil views:views]]; 

    //Comment entry input 
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[commentInput]-0-|" options:0 metrics:nil views:views]]; 

    commentInputVerticalConstraint = [NSLayoutConstraint constraintWithItem:self.commentEntryInput 
                   attribute:NSLayoutAttributeHeight 
                   relatedBy:NSLayoutRelationEqual 
                    toItem:nil 
                   attribute:NSLayoutAttributeHeight 
                   multiplier:1.0 
                   constant:commentInputHeight]; 

    if(commentInputBottomConstraint == nil) 
    { 
    commentInputBottomConstraint = 
    [NSLayoutConstraint constraintWithItem:self.commentEntryInput 
           attribute:NSLayoutAttributeBottom 
           relatedBy:NSLayoutRelationEqual 
            toItem:self.view 
           attribute:NSLayoutAttributeBottom multiplier:1.0 
            constant:0.0]; 

    } 

    [self.view addConstraint:commentInputVerticalConstraint]; 
    [self.view addConstraint:commentInputBottomConstraint]; 

    [super updateViewConstraints]; 
} 

Теперь у меня есть метод, который вызывается, когда keyBoardWillShow называется. Этот метод анимирует управление вводом комментариев, когда появляется клавиатура.

(void)animateContentWithKeyboardInfo:(NSDictionary *)keyboardInfo 
    { 
     NSNumber    *animationDuration = keyboardInfo[ UIKeyboardAnimationDurationUserInfoKey ]; 
     NSValue     *keyboardFrameValue = keyboardInfo[ UIKeyboardFrameEndUserInfoKey ]; 
     CGRect     keyboardFrame  = [keyboardFrameValue CGRectValue]; 
     UIViewAnimationCurve animationCurve  = [keyboardInfo[ UIKeyboardAnimationCurveUserInfoKey ] intValue]; 

     UIViewAnimationOptions animationOptions = animationOptionWithCurve(animationCurve); 

     commentInputBottomConstraint.constant = (keyboardFrame.origin.y - [UIScreen mainScreen].bounds.size.height); 

     //Increase the veritcal height of the comment input control 
     commentInputVerticalConstraint.constant = 125; 

     //Takes into account that the Tab Bar is 50 points, and adjust for this 
     //value. 

     if(keyboardAppeared == YES) 
     { 
     commentInputBottomConstraint.constant += TAB_BAR_OFFSET; 
     } 

     else 
     { 
     commentInputBottomConstraint.constant -= TAB_BAR_OFFSET; 
     } 

     [self.view layoutIfNeeded]; 

     [self.view setNeedsUpdateConstraints]; 

     [UIView animateWithDuration:[animationDuration floatValue] delay:0.0 options:animationOptions animations: 
     ^{ 


     [self.view layoutIfNeeded]; 

     } completion:nil]; 
    } 

Однако, когда я пытаюсь настроить константу в commentInputVerticalConstraint я получаю сообщение об ошибке:

Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the `UIView` property `translatesAutoresizingMaskIntoConstraints`) 
(
    "<NSLayoutConstraint:0x1899fcb0 V:[CommentEntryInput:0x176e5160(50)]>", 
    "<NSLayoutConstraint:0x1899e5c0 V:[CommentEntryInput:0x176e5160(125)]>" 
) 

я не уверен, есть ли способ для меня «сбросить» или отрегулируйте ограничение, которое нужно обработать, когда появится клавиатура, а затем верните ее в нормальное состояние, когда клавиатура исчезнет. Любая помощь будет оценена по достоинству.

ответ

1

Ваша проблема заключается в том, что -(void)updateViewConstraints получает вызов более одного раза. Таким образом, вы создаете новое ограничение и дважды добавляете его в представление. Попробуйте проверить, нет ли ограничения или нет.

Я также не думаю, что вам нужно первое [self.view layoutIfNeeded] перед изменением анимации константы. При изменении константы просто установите его, затем оберните [self.view layoutIfNeeded] в блок анимации, чтобы оживить это новое значение.

Смежные вопросы